0
votes

I have a file that defines a trait and its companion object.

trait SomeTrait {
}

object SomeTrait extends SomeConfig {
 implicit def intToString(v: Int): String = v.toString
}

In another file, I have a case class that extends a trait along with the one above.

case class SomeCaseClass extends AnotherTrait with SomeTrait {

  protected def someLoginc(): Unit = {
   // The compiler cannot find the implicit def intToString 
  }
}

How come the compiler cannot find the implicit defined in the companion object?

As per my understanding, the implicits defined in a companion object are automatically brought into the scope.

1

1 Answers

2
votes

As per my understanding, the implicits defined in a companion object are automatically brought into the scope.

No, the compiler looks into the companion objects of the types involved in the conversion and their parts. E.g. in Where does Scala look for implicits? Companion Objects of a Type:

First, the object companion of the “source” type is looked into... Second, the companion object of the expected type... Note that companion objects of super classes are also looked into...

I.e. for this rule to work for intToString, it would need to be declared in the companion object of Int, String, or one of their supertypes (which of course you can't do).