Lazy implicit val not found

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 } 

specific class foo

FWIW I am stuck on scala 2.10 for this application. Also, replacing lazy val with def does not seem to change anything.

In my actual application, I have a file with a bunch of implications defined for different domain objects, some of which depend on each other. It seems like a nightmare to try to organize them in such a way that all dependencies come to their dependents, so I designated them as lazy . To explicitly declare the type of each of these vals muddies up the code, and it seems like this should be unnecessary. How to get around this?

+6
source share
1 answer

Why can't scala find the implicit here?

I applied a somewhat more permissive rule: an implicit conversion without an explicit result type is visible only in the text, following its own definition. Thus, we avoid cyclic reference errors. I am closing now to see how it works. If we still have problems, we return to this.

To explicitly declare the type of each of these vals muddies up the code, and it seems that this should not be unnecessary.

In particular, for phenomena, I recommend doing it nonetheless. This question is not the only reason; if in the future the type of implicit changes are unintentional, this can break compilation in difficult ways. See also the problem related above:

Martin wrote on the scala -user list: β€œIn general, it’s a good idea to always write the result type for the implicit method. Perhaps the language should require it.”

I was bitten several times by problems that were gone when I added the result type to implicit, so I thought that I would open a ticket for this.

+3
source

All Articles