简体   繁体   中英

Scala implicit argument's type finding fail

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM