Implicit is another exciting and powerful feature introduced by Scala, and it can refer to two different things:
- A value that can be automatically passed
- Automatic conversion from one type to another
- They can be used for extending the capabilities of a class
Actual automatic conversion can be accomplished with implicit def, as seen in the following example (supposing you are using the Scala REPL):
scala> implicit def stringToInt(s: String) = s.toInt
stringToInt: (s: String)Int
Now, having the preceding code in my scope, it's possible for me to do something like this:
scala> def add(x:Int, y:Int) = x + y
add: (x: Int, y: Int)Int
scala> add(1, "2")
res5: Int = 3
scala>
Even if one of the parameters passed to add() is a String (and add() would require you to provide two integers), having the implicit conversion in scope allows the compiler...