Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

scala

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

like image 792
Tom Avatar asked Apr 20 '11 18:04

Tom


1 Answers

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.

like image 115
Daniel C. Sobral Avatar answered Dec 02 '22 17:12

Daniel C. Sobral