开发者

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...


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(_))


You have declared an existential type:

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

is equivalent to

def apply(entries: TypedPair[t] forSome { type t }*) = entries.foreach(process)

I'm not sure if this is what you intended or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜