lazy implicit val not found
Asked Answered
D

1

7

Why can't scala find the implicit here?

class A

class Foo {
  lazy val x = implicitly[A]
  implicit lazy val a = new A
}

error: could not find implicit value for parameter e: A

But this works just fine:

class Foo {
  lazy val x = implicitly[A]
  implicit lazy val a: A = new A // note explicit result type
}

defined class Foo

FWIW I'm stuck on Scala 2.10 for this application. Also, replacing lazy val with def doesn't seem to change anything.

In my actual application, I've got a file with a bunch of implicits defined for various domain objects, some of which depend on each other. It seems like a nightmare to try and arrange them in a way that makes sure all dependencies come before their respective dependents, so I marked them all as lazy. Having to explicitly declare the type of each of these vals muddies up the code, and seems like it should be unnecessary. Any way around this?

Divisibility answered 13/10, 2015 at 14:10 Comment(2)
This happens with Scala2.11 too. As you said, correct order does work implicit lazy val a = new A; lazy val x = implicitly[A]. Shouldn't this be a bug in Scala ?Bathsheeb
If you move the implicitly call to be after the implicit lazy val definition it compiles without needing to add the type annotation.Scalp
A
3

Why can't scala find the implicit here?

I have implemented a slightly more permissive rule: An implicit conversion without explicit result type is visible only in the text following its own definition. That way, we avoid the cyclic reference errors. I close for now, to see how this works. If we still have issues we migth come back to this.

Having to explicitly declare the type of each of these vals muddies up the code, and seems like it should be unnecessary.

For implicits specifically, I recommend doing so nonetheless. This issue isn't the only reason; if in the future type of an implicit changes unintentionally, this can break compilation in hard-to-understand ways. See also the issue linked above:

Martin wrote on the scala-user list, "In general it's a good idea always to write a result type for an implicit method. Maybe the language should require it."

I've been bitten myself a couple times by problems that went away once I added a result type to an implicit so I thought I'd open a ticket on this.

Adnate answered 13/10, 2015 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.