In my first consulting assignment in Scala, the most frustrating piece of code was the one involving implicit keyword. There was a portion of code written by the client and the team was huffing and puffing trying to understand the code.
implicit keyword in Scala gives the flexibility of using variables and methods that are implicitly defined. Confusing?. While it’s a good feature if used judiciously, it can become a bane when overused. Let’s take this code as example.
def add(a:Int)(implicit b:Int) = a+b add(12)
In the code above, b is defined as an implicit variable. And we invoke the function by passing only one value. What does that mean? The add function looks for another Int that is implicitly defined in the code(!) and uses it. But now that we have not defined it; Scala compiler gives an error stating, could not find implicit value for parameter b: Int. We can make this code work by writing this.
implicit val x:Int = 14 def add(a:Int)(implicit b:Int) = a+b add(12)//Prints 26
Since we have defined an implicit integer variable x, compiler automatically picks it up and passes it as the second argument of add function.
So what happens if we have more than one implicit variable? You can try that out and see