Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazy implicit val not found

Tags:

scala

implicit

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?

like image 729
Dylan Avatar asked Oct 13 '15 14:10

Dylan


People also ask

What is a lazy val in Scala?

Scala provides a nice language feature called lazy val that defers the initialization of a variable. The lazy initialization pattern is common in Java programs. Though it seems tempting, the concrete implementation of lazy val has some subtle issues.

What is implicit Val in Scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.


1 Answers

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.

like image 192
Alexey Romanov Avatar answered Oct 07 '22 00:10

Alexey Romanov