mercredi 6 avril 2016

scala generic type inference inconsistent with ClassTag

I'm using scala 2.10, and have found what I consider weird behaviour when using type inference for generic paramters. Consider the example below (note i is just a dummy variable):

scala> import scala.reflect.{ClassTag,classTag}

def broken[T : ClassTag](i : Int) : List[T] = {
  println("ClassTag is : " + classTag[T])
  List.empty[T]
}
import scala.reflect.{ClassTag, classTag}

scala>      |      |      | broken: [T](i: Int)(implicit evidence$1: scala.reflect.ClassTag[T])List[T]

scala> broken(3)
ClassTag is : Nothing
res0: List[Nothing] = List()

scala> val brokenVal : List[String] = broken(3)
ClassTag is : Nothing
brokenVal: List[String] = List()

The call broken(3) seems consistent, in that the print statement inside the function agrees with the inferred ClassTag.

However, the second statement, there is an inconsistency between what the compiler infers for the ClassTag, and is printed inside the function, and what the actual return type is.

I would have expected the compiler to infer the ClassTag from the type declaration i.e. List[String]. Is this not correct? Can somebody enlighten me?

Some further context here: I'm actually using the classtag to filter a collection in some code (not shown here), and it's obviously failing when I don't specify T explicitly, as it's comparing against type None.





Aucun commentaire:

Enregistrer un commentaire