Implicit conversions in Scala are cool

Andy Warhol  Dollar sign

Sometimes I hear sentences like Domain Specific Languages (DSL) can be generated effectively only using dynamic languages, or This super-cool feature could not be possible in a static typed language. More and more, some people would transmit the idea that dynamic languages are agile and cool, while static ones are rigid and old. I strongly disagree! I think that in static languages lots of unit tests are generated and maintained automatically by the compiler, while in dynamic ones the programmer should create and maintain these tests. So static languages have lots more unit tests: isn't this agile programming? And what about cool features? Well, what do you think about a language in which you can write something like this?

 
(5.0 USD) + (2.0 USD) == (7.0 USD)

Cool DSL, isn't it? Sure, and I will show you that this is possible (and very easy) using a language with a strong and static type system: Scala.

As we are going to write yet another money example, we could begin with the definition of currencies.

 
abstract class Currency {
  def name: String;
  override def toString = name
}    
 
object Euro extends Currency {
  def name ="EUR"
}    
 
object Dollar extends Currency {
  def name = "USD"
}

Not very exciting. We simply define an abstract Currency class and two singleton objects that extend this class. Note that these objects are instances of anonymous subclasses of Currency. This does matter, as we'll see in a moment.

Now let's define money.

 
case class Money[C <: Currency](amount: Double, currency: C) {
  def + (otherMoney: Money[C]) = {
    new Money(amount + otherMoney.amount, currency)
  }
  override def toString = amount + " " + currency
}

Our class is parametric in the type C, and we tell to the compiler that it must be a subclass of Currency. This way we have the nice consequence that the + operator can add only money of the same currency, and this test is done by the compiler before our code is running.

It's time to get to the cool feature: implicit conversion. So, in the same file Money.scala in which we defined the Money class, we create a Money object, which has the responsibility to convert doubles, let me say, "annotated" with a currency, into Money.

 
object Money {
  implicit def doubleConverter(d: Double) = new {
    def EUR = {
      new Money(d, Euro)
    }    
 
    def USD = {
      new Money(d, Dollar)
    }
  }
}

Uhm, it sounds a bit strange. How we can use it? Let's see an example.

 
import Money._    
 
object MoneyMainProgram extends Application {    
 
  val tenDollars = (4.0 USD) + (6.0 USD)     
 
  println(tenDollars)
}

Now some explanations are required.

In the first line we import the Money object. We can see it as a kind of static import, that, among other things, adds to the scope of our code all the implicit conversions defined in that object.

When we write 4.0 USD, we try to invoke the USD method on the 4.0 object, which is a double. Obviously there isn't such a method in the Double class, but the compiler, before giving up and throwing an error, tries to see if there is some way to convert the 4.0 in an object that does understand the USD method. Luckily we have imported the doubleConverter which takes a Double and transforms it in an instance of an anonymous class with a USD method: bingo! So the compiler transforms our code in something like this:

 
  doubleConverter(4.0).USD()

But what is the result of this expression? Well, it's an instance of the Money class expressed in Dollar. This class has the + method that we can use to add another Money in the same currency. Cool!

Let's take a look to our work. We needed to add some features to the Double class. In some dynamic languages we could monkey patch this class. In Scala we did it using a dynamic conversion from Double to a class with the methods we need, so we reached the same purpose in a static and safer way.

And so, an old fashioned static language could have such cool features? It seems....

Lascia un commento

You must be logged in to post a comment.