找不到惰性隐式 val

lazy implicit val not found

为什么 scala 在这里找不到隐含的?

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

但这工作得很好:

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

defined class Foo

FWIW 对于此应用程序,我坚持使用 Scala 2.10。此外,用 def 替换 lazy val 似乎没有任何改变。

在我的实际应用程序中,我有一个文件,其中包含为各种域对象定义的一堆隐式,其中一些相互依赖。尝试以一种确保所有依赖项都在其各自依赖项之前的方式来安排它们似乎是一场噩梦,所以我将它们全部标记为 lazy。必须显式声明每个 val 的类型会使代码变得混乱,而且似乎没有必要这样做。有什么解决办法吗?

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.

必须显式声明每个 val 的类型会使代码变得混乱,而且似乎没有必要。

对于具体的隐式,我还是建议这样做。这个问题不是唯一的原因;如果将来隐式的类型无意中改变,这可能会以难以理解的方式破坏编译。另请参阅上面链接的问题:

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.