Scala unfortunately still has to deal with type erasure at runtime in the JVM. However, a couple of things have been cleaned up with respect to generics:
- Type parameters are non-optional (no
List
, onlyList<String>
/List[String]
) - Language support for co-/contravariance
Further, to deal with the limitations of the JVM TypeTags
(in 2.9 Manifests
) can be used to store type information that would otherwise be lost at runtime. For example:
import scala.reflect.runtime.universe._
def foo[T : TypeTag](x: List[T]) = {
println(implicitly[TypeTag[T]].tpe)
}
This prints the type of the elements of the list. Something which would be irrecoverably lost, if - for example - you pass an empty list:
foo(List.empty[String])
// not distinguishable without TypeTags from
foo(List.empty[Int])