Sunday, February 27, 2011

Scala implicit conversion

Implicit conversion helps us to convert between types without explicitly calling conversion methods. Let's take a look at following example.

We have a list of names.
val xs = List("John", "Jack", "Boby")
If we assign it to a string value, scala will complain that there is a type mismatch error.
scala> val s : String  = xs  
<console>:6: error: type mismatch;
 found   : List[java.lang.String]
 required: String
       val s : String  = xs

Let's define the implicit conversion here.

implicit def list2String(l: List[String]) = l.foldLeft(""){ (sum, x) => sum + x + (if (x == l.last) "" else ", ")}
and let's try the assignment now.
scala> val s: String = xs
s: String = John, Jack, Boby


It saves a lot time and code. But we have to follow several rules.

Implicit conversion rules
  1. Marking Rule: Only definitions marked implicit are available.
  2. Scope Rule: An inserted implicit conversion must be in scope as a single
    identifier, or be associated with the source or target type of the conver-
    sion.
  3. Non-Ambiguity Rule: An implicit conversion is only inserted if there is
    no other possible conversion to insert.
  4. One-at-a-time Rule: Only one implicit is tried.
  5. Explicits-First Rule: Whenever code type checks as it is written, no implicits are attempted.
Look at Predef methods. It has a number of implicit converters which imported automatically.

Reference:
Programming in Scala by Martin Odersky, Lex Spoon, Bill Venners

No comments:

Post a Comment