Saturday, 30 August 2008

Scala and implicit conversion: Turning a string into pure Weirdness

In the Scala programming language, you can turn water into wine, or vice versa, using implicit conversion.

Imagine that you have a class called Weird:


class Weird(s :String) {
def imWeird :String = {
"I'm "+ s +" and I'm weird!"
}
}

It consists of merely a string, s, and a method, imWeird, that returns a jolly message containing the very same string. (Thus, the code
val freak = new Weird("a freak")
println(freak.imWeird)
outputs I'm a freak and I'm weird!.)

Now, Scala allows you to create an implicit conversion that adds the method(s) of Weird to any other class. Or rather, turns an object into a Weird whenever one calls Weird's methods (functions) on the given object.

For example, the following implicit conversion
  implicit def string2Weird(s: String) = new Weird(s)
makes it possible to call Weird's method(s) on a String. This code
val happy = "Happy"
println(happy.imWeird)
will now output
  I'm Happpy and I'm weird!

The name of the implicit conversion method, string2Weird, is arbitrary.