foo[T](T,T): T 的 Scala 类型扩展/推理
假设有三个函数:
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(), "")
按预期工作
Assume there are three functions:
def foo[T](a:T, b:T): T = a
def test1 = foo(1, "2")
def test2 = foo(List(), ListBuffer())
While test1 is of type Any, test2 does not compile. Why is that? Both List() and ListBuffer() are of type Any, so why is test2 is not of type Any as well? Also both of them are of type SeqFactory, so can Scala somehow infer that type of test2 is SeqFactory?
foo(ListBuffer(), "")
and foo(List(), "")
work as expected
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我来说看起来像一个错误。 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]
并不真正适合该类型。Looks like a bug to me. Scala first infers
Seq[Nothing]{def seq: Seq[Nothing]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}; def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}
, and then decidesListBuffer[Nothing]
doesn't really fit that type.