Scala类型扩展/推断foo [T](T,T):T

时间:2011-04-20 18:14:07

标签: scala types

假设有三个功能:

def foo[T](a:T, b:T): T = a 
def test1 = foo(1, "2") 
def test2 = foo(List(), ListBuffer()) 

虽然test1的类型为Any,但test2不会编译。这是为什么? List()和ListBuffer()都是Any类型,那么为什么test2也不是Any类型呢?它们都是SeqFactory类型,因此Scala能否以某种方式推断出test2的类型是SeqFactory?

foo(ListBuffer(), "")foo(List(), "")按预期工作

1 个答案:

答案 0 :(得分:3)

对我来说看起来像个错误。 Scala首先推断Seq[Nothing]{def seq: Seq[Nothing]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}; def companion: scala.collection.generic.GenericCompanion[Seq[Any]]},然后判定ListBuffer[Nothing]不适合该类型。