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!
The problem stems from the fact that the implicit
FooWorker.list
does not have an explicitly declared type. If you complete the line to: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.