开发者

Scala type-widening/inference of foo[T](T,T): T

开发者 https://www.devze.com 2023-02-27 04:01 出处:网络
Assume there are three functions: def foo[T](a:T, b:T): T = a def test1 = foo(1, \"2\") def test2 = foo(List(), ListBuffer())

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开发者_如何学Go them are of type SeqFactory, so can Scala somehow infer that type of test2 is SeqFactory?

foo(ListBuffer(), "") and foo(List(), "") work as expected


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 decides ListBuffer[Nothing] doesn't really fit that type.

0

精彩评论

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