Implicit resolution for different orders of case class and companion

379 views Asked by At

Usually, I write first a case class and then the companion object in the same file, right below. But when trying to import an implicit declared in the companion, I'm forced to switch the order of declaration (and I don't want, obviously). What is the recommended practice to overcome this situation?

For a concrete case, the following code doesn't work:

  object SomeLib {
     def doSomething[T : List](t: T) = "meh"
  }

  case class FooWorker(x: String) {
    import FooWorker._ // bring the implicit in scope for doSomething
    def then(event: String) : FooWorker = {
      copy(x = SomeLib.doSomething(event)) // requires implicit
    }
  }

  object FooWorker {
    implicit val list = List("a", "b", "c")
  }

But if I declare object FooWorker before case class FooWorker it does work. I'm using Scala 2.11.6 and SBT to test. Thanks a lot!

2

There are 2 answers

1
Martin Odersky On BEST ANSWER

The problem stems from the fact that the implicit FooWorker.list does not have an explicitly declared type. If you complete the line to:

implicit val list: List[String] = List("a", "b", "c")

everything works as expected, regardless of order of declarations. In general, you should always give an explicit type for an implicit value. This rule will be enforced in a future version of Scala.

0
Régis Jean-Gilles On

This is an open bug.

See https://issues.scala-lang.org/browse/SI-5197 (and related/duplicate issues).