Wednesday, 2 December 2009

A bit of Scala a day keeps Java at bay: Traits

The title of this blog post may seem a bit controversial to some, but the more I learn about Scala, the less I feel enclined to go back to Java. I had similar feeling when learning Groovy, but then again knowing Scala, I don't think I want to go back to Groovy either.

Today, I am going to cover the surface of Scala traits which can be thought as Java interfaces on steroids. Traits encapsulate fields and methods definitions in units which can be easily composed when creating classes. Scala does not support multiple class inheritance but achieves a similar result by allowing you to mix in as many traits as you want. Here is an example with 2 traits and a class that mixes them in.

And then you can just invoke methods from trait A and B which have been imported in C.

And the output is:

A very useful property of Traits is that they are stack-able. A trait can invoke any method or field which belong to the trait or class which precedes it in the hierarchy, as long as their types are compatible. An example is probably better than a long winded explanation:

Which outputs:

Those examples are quite simple, but I do hope they get the point across. I've used Trait in my PubSubHubBub client for composing Restlets from Traits which individually handle HTTP verbs like GET, POST, DELETE, etc.. If you want to find out more, the code is at:

1 comment:

  1. Guillaume, hopefully you are still active on this blog. I would like to discuss a Cloud/Scala/Current technology question with you.
    I would be more than happy for you to contact me on my email

    kind regards