2

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 ?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Wow, Thanks a lot ! That was exactly the problem. The method name should already exist on the object before implicits are applied.
very interesting, when this kind of resolution would be useful?
@Mikel; that's a good question. I don't know how/why the implicit scoping rules were decided upon. I was a bit surprised to learn about this one.
I tried to use String as type (of the field n), and use method name product (instead of mul). Now it won't compile again. How can we explain this one? If there's a type-parameter it won't work?
If you're changing from conversion-from-Int to conversion-from-String then the method name needs to be something that already exists in the String class, but not all methods appear to work. Methods like split() and length() work while methods like product(), drop(), and head() don't. I don't know why. It might have something to do with which methods are native to the java.String class and which are added by the Scala StringOps wrapper, but that's only a guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.