Search code examples
scalawildcardtype-parameter

Why can't a wildcard type parameter is Scala be bound?


I have a typed pair class:

class TypedPair[T]

and I want to apply a certain function to a heterogeneous sequence of them:

def process[T](entry: TypedPair[T]) = {/* something */}

Why doesn't this work?

def apply(entries: TypedPair[_]*) = entries.foreach(process)

It fails with the error:

error: polymorphic expression cannot be instantiated to expected type;
 found   : [T](TypedPair[T]) => Unit
 required: (TypedPair[_]) => ?
         def apply(entries: TypedPair[_]*) = entries.foreach(process)

I don't recall getting into this problem in Java...


Solution

  • The compiler has problems figuring out the anonymous method in this case. When you added the dummy parameter, you also changed the syntax to help the compiler with it, so the following will work:

    def apply(entries: TypedPair[_]*) = entries.foreach(process(_))