假设有三个功能:
def foo[T](a:T, b:T): T = a
def test1 = foo(1, "2")
def test2 = foo(List(), ListBuffer())
Run Code Online (Sandbox Code Playgroud)
虽然test1的类型为Any,但test2不会编译.这是为什么?List()和ListBuffer()都是Any类型,那么为什么test2也不是Any类型呢?它们都是SeqFactory类型,因此Scala能以某种方式推断出test2的类型是SeqFactory吗?
foo(ListBuffer(), "")并按foo(List(), "")预期工作
对我来说看起来像一个错误。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]并不真正适合该类型。