Reputation: 372
I had some code:
def sum1(x: Int)(y: Int) = x + y
and
def sum2(x: Int)(implicit y:Int) = x + y
Could you please explain for me which case will use sum1 and sum2?
Thank you!
Upvotes: 0
Views: 31
Reputation: 12794
In order to call a function with an implicit parameter, exactly one value with a type matching the implicit parameter must exist in the implicit scope.
Here are some very easy examples:
def implicitSum(n: Int)(implicit m: Int): Int = n + m
val a = {
implicit val a = 2
implicitSum(1) // equals 3
}
val b = {
implicit val b = 3
implicitSum(1) // equals 4
}
val c = {
implicit val c = 4
implicitSum(1)(1) // equals 2: explicit parameter has higher priority
}
val d = {
implicitSum(1) // does not compile, no implicit (or explicit) parameter
}
As you may understand from the examples, implicit resolution is done at compile time.
To know more on the topic (and to have some more interesting and meaningful examples) I suggest reading this page of the Scala documentation.
Upvotes: 0