Reputation: 978
Trying to understand this case of implicit finding - finding implicit of an argument's type. I copy-pasted the official example into the IDE and just changed the method name to mul like this:
class A(val n: Int) {
def mul(other: A) = new A(n + other.n)
}
object A {
implicit def fromInt(n: Int) = new A(n)
}
1 mul (new A(1))
Now it results in a compile-error saying:
value mul is not a member of Int
I also tried to experiment with String instead of Int which again resulted in compile error.
Can you explain what part I am doing wrong ?
Upvotes: 2
Views: 69
Reputation: 51271
The difference between def +(other: A) =...
and def mul(other: A) =...
is that Int
has a +
method but it does not have a mul
method.
If the method exists, but not for the argument type being passed, then the compiler will look for an implicit conversion. Included in the implicit scope is the companion object of the passed parameter argument. If the implicit conversion is found then the entire expression is assessed for conversion.
If the method does not exist then an implicit conversion in the companion object is not within the implicit scope. It won't be found and no conversion takes place.
If you were to move the implicit def fromInt(...
outside of the companion object then the mul()
conversion will take place.
Upvotes: 3