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

5 comments:

  1. When I was little, I always imagined and dreamed that I would be able to write a resume perfectly, but it didn’t work out, although I found this site https://paulbender.gumroad.com/p/what-did-you-forget-to-add-to-your-resume, it is about writing a resume and other services

    ReplyDelete
  2. I appreciate you taking the time to make this insightful essay. It has taught me a lot to read this. Keep up the fantastic work! I can't wait to read your next posts. Your carefully considered and researched information is always enjoyable to read.
    Reckless Driving In New Jersey

    ReplyDelete