2010-03-25

Scala 2.8 Showcase - Type Specialization

Scala 2.8 introduces type specialization. Because Scala is based on JVM, type erasure occurs. Type erasure is a bummer, but it has to be there for backwards compatibility with older Java versions.

Backwards compatibility is an important asset (for Java), but the downside of type erasure is (among others) that in case of primitive types autoboxing is used extensively which causes developers to favor non-generic classes over generic ones (for performance reasons; autoboxing is quite slow).

Now, Scala 2.8 has a solution for this, and that's a new annotation called @specialized.

class MyCollection [@specialized A]{
    def simplyReturn(x: A): A = {
        x
    }
}

What it does is it causes the compiler to generate specialized versions for primitives, so that autoboxing does not have to occur, which is faster. I should investigate the performance difference in future and share the results!

You can also specify which primitive classes should be specialized.

class MyCollection [@specialized("Int") A]{
    def simplyReturn(x: A): A = {
        x
    }
}

Read more about it in the official Scala document (PDF).

Scala 2.8 Showcase


  1. Scala 2.8 Showcase - Collections
  2. Scala 2.8 Showcase - Arrays
  3. Scala 2.8 Showcase - Type Specialization

4 comments: