A Look at Scala Implicit Conversions

An example of converting mechanical energy to heat.
An example of converting mechanical energy to heat.

One of the nice things about Scala is its ability to hack the language. An “implicit conversion” is one way to do this. Here’s a short example.

A common way to get readable code around squaring an integer is to define a function that takes an integer parameter and returns the value multiplied by itself. In Scala that looks like this:

def square(x: Int) = x * x

This forces us to perform calculations against square numbers in a syntax we don’t usually use:

2 + square(2)

When we talk about squares of numbers in the real world we don’t usually say something like “two plus square two.” We say “two plus two squared.” Lucky for us, Scala has our back on this problem.

It is interesting to think about the fact that all primitives are objects in Scala. Since integers are objects they themselves can have methods. For example, this is a perfectly valid Scala command:

2.toString

Scala’s treatment of all primitives as objects means we can call methods on an Int. It isn’t a far leap to think what if we added a “squared” method. But how can we do that?

We simply define an implicit!

import scala.language.implicitConversions

class IntMethods(x: Int) {
def squared = x * x
}

implicit def IntWrapper(x: Int) = new IntMethods(x: Int)

This code snippet creates a class with a squared function called IntMethods. It then creates an “implicit” named IntWrapper which takes an integer.

Now we can write code that mirrors the English language more closely:

2 + 2.squared

Actually we don’t even need the dot:

2 + (2 squared)

When the compiler encounters “2 squared” it sees that there is no “squared” method on the Int class so it looks for an implicit that matches. It finds the IntWrapper implicit, looks in the object and sees “squared,” and runs the method.

If you have programmed in Scala even a little bit, you have probably unwittingly used implicit conversion. Have you ever tried something like this?

1 to 4 foreach println

If you enter the Scala interpreter and type “1.” and then hit the tab key, you’ll see all the methods that belong to Int. Notice that “to” isn’t one of them. Yet in the above snippet you can type “1 to 4” and it works just fine. This is because there is an implicit conversion to the RichInt class, which does have the “to” method.

Scala is interesting because it allows some ways to program in more real-world language. Implicit conversion is one of those ways!

One thought on “A Look at Scala Implicit Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *