Another Tour of Scala

ImplicitConversions

The Gist

There is no tour for this, and it makes the tour element for Implicit Parameters baffling.

My Interpretation

In Scala, one can convert between types implicitly by providing the conversion code. The simplest example of this is converting from strings to actual types. Suppose you are processing configuration data and wish to treat the strings as their actual types; numbers become numbers and “true” or “false” becomes a boolean.

In Java, you would need a complex system of type analysis and conversion logic to figure out a) what the type to convert to is, and b) how to do the conversion.

In Scala, you can define a function as implicit and it will be used to attempt a conversion:

Without the two implicit method definitions, Scala would raise compile errors when assigning strings to the non-string properties of Configuration.

Instead, it looks for a method that takes what it has, and gives what it needs. In the case of the first assignment, Scala knows we need a Boolean and it knows we have a String. Since str2bool takes a String and returns a Boolean, it applies it to get the value. We could even get fancier:

Here, we implicitly convert from a string to our simple URL class; that conversion method takes advantage of our str2int method to set the port number.

My Thoughts on this Feature

I like this, although I can see it becoming banned on large projects because it obfuscates the flow of control through a program quite a bit. Still, I would use this feature a lot.