Search code examples
scalacompilationjvmtype-erasure

Scala's "clean up" of type erasure


I have just begun investigating Scala and found the following perplexing quote in the Wikipedia page on Scala:

[Scala] cleans up [...] poor design decisions in Java (e.g. type erasure...

I thought type erasure was a limitation imposed by the Java Virtual Machine, so given that the JVM executes Scala code, how has this been "cleaned up"?

I do appreciate that the designer of Scala also contributed to the JVM, so I am curious to understand if he / the Scala team has augmented the Scala compiler to carry rich run-time type information and thus 'clean up' type erasure. Is this the case?

Thanks in advance for any insight you can provide.


Solution

  • 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, only List<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])