A function can have implicit
parameters in Scala, marked by the implicit
keyword at the beginning of the parameter list. If the parameter is not passed, as usual, the compiler looks for an implicit
value of the correct type and passes it as the function’s argument.
def f1(implicit x:Int, y:String) // x and y are implicit
def f2(y:String)(implicit x:Int) // only x is implicit
In the following example, we define the function sum
using the implicit
keyword in the parameters. As demonstrated by the output, the compiler searches for the value toAdd
by itself.
We can also provide the value to the sum
function despite the arguments defined as implicit
. This is demonstrated in line 8, where we provide the value to the sum
function. We can see this here:
val val1 = 50 implicit val val2 = 120 def sum(implicit toAdd: Int) = val1 + toAdd // Implicit parameter will be passed here val result = sum // We provide an explicit parameter here val result2 = sum(50) println(result) println(result2)
RELATED TAGS
CONTRIBUTOR
View all Courses