为什么不能将通配符类型参数绑定到Scala?

时间:2010-11-29 10:07:22

标签: scala wildcard type-parameter

我有一个打字对类:

class TypedPair[T]

我希望将某个函数应用于它们的异构序列:

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

为什么这不起作用?

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

失败并显示错误:

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

我不记得在Java中遇到这个问题...

2 个答案:

答案 0 :(得分:3)

在这种情况下,编译器在找出匿名方法时遇到了问题。添加伪参数时,您还更改了语法以帮助编译器使用它,因此以下内容将起作用:

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

答案 1 :(得分:0)

您已声明存在类型:

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

相当于

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

我不确定这是不是你想要的。