Implicits allow you to do magic in Scala. With great power comes great responsibility. Implicits allow to you create very powerful DSL, but they also allow you to get crazy, so do it with wisdom. You are allowed to have implicit functions, classes, and objects. The Scala language and other core frameworks from the Scala ecosystem like Akka and PlayFramework use implicits many times.
$ scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala> implicit def transformStringtoInt(n:String) = n.toInt warning: there was one feature warning; re-run with -feature for details transformStringtoInt: (n: String)Int scala> scala> val s:String = "123456" s: String = 123456 scala> println(s) 123456 scala> scala> val i:Int = s i: Int = 123456 scala> println(i) 123456 scala>
To use implicits, you need to use the keyword implicit
before a function. Scala will implicitly call that function when it is appropriate. For this case, it will call to convert the String
type to Int
type as we can see.
$ scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala> implicit val yValue:Int = 6 yValue: Int = 6 scala> def sum(x:Int)(implicit yValue:Int) = x + yValue sum: (x: Int)(implicit yValue: Int)Int scala> val result = sum(10) result: Int = 16 scala> println(result) 16 scala>
For this other case, given in the last code, we use an implicit parameter in the function sum
. We also used a curried function here. We defined the implicit
function first, and then called the sum
function. This technique is good for externalized functions configuration and values you would let it hard code. It also saves lines of code, because you don't need to pass a parameter to all functions all the time, so it's quite handy.