March 21, 2013

Learning Scala

I‘m really learning Scala, in depth this time. Indeed, I‘ve been reading Programming in Scala these days.

While learning it I discovered what are implicits, and how cool they are. I’ll let you discover what they are by reading the [following article][1] since they explain that way better than me.

A cool use of implicits is that you can extend the Scala language with cool new syntaxes features, for example what if you like the Python’s in operator ?

What if you would like to have it in Scala to check if a Map contains a specific key ?

With implicits it is really easy to add that kind of feature. Let‘s see how we would do that.

// Declare an helper class that contains the method(s) we would like to add to Map
class MapHelper[T](o: T) {
    def in(map: Map[T, Any]) = map.contains(o)
}

// Declare our implicit that will wrap anything left to `in` into an Expression
// so that `in()` is bound and can be called by Scala automatically
implicit def mapHelperWrapper[T](o: T) = new MapHelper(o)

// output "true"
("a" in Map("a" -> "b")) println

// output "false"
("foo" in Map("bar" -> "foo")) println

What happens is that Scala replace our call with the following, automagically:

println(new MapHelper("a").in(Map("a" -> "b"))

This is really a short example, but a lot of things can be made easy with this feature. For instance:

Map("foo" -> "bar")
// -> is really an implicit that let you write Maps easily

There seems to be no limit but your imagination !

Scalocco

In order to learn I wrote a quick implementation of http://jashkenas.github.com/docco/ in Scala.

You can find it on my GitHub repository http://github.com/agrison/scalocco/. For the moment it supports only one-line comments (using //)

but should soon extract params and results from scaladoc in order to present them using tables rendered as HTML.

Scala is cool

Yes you already know that. Scala is cool, and I hope I‘ll have the chance to learn it better and better, and maybe use it in my day to day work.

Maybe it will be widely used in Luxembourg soon, maybe it is already ? We‘ll see.

Enjoy :)

Alexandre Grison - //grison.me - @algrison