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
- Marking Rule: Only definitions marked implicit are available.
- 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. - Non-Ambiguity Rule: An implicit conversion is only inserted if there is
no other possible conversion to insert. - One-at-a-time Rule: Only one implicit is tried.
- Explicits-First Rule: Whenever code type checks as it is written, no implicits are attempted.
Reference:
Programming in Scala by Martin Odersky, Lex Spoon, Bill Venners