scala - 找不到懒惰的隐式 val

标签 scala implicit

为什么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 上。另外,替换 lazy valdef似乎没有改变任何东西。

在我的实际应用程序中,我有一个文件,其中包含为各种域对象定义的一堆隐式,其中一些相互依赖。尝试以确保所有依赖项排在其各自依赖项之前的方式排列它们似乎是一场噩梦,因此我将它们全部标记为 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.

关于scala - 找不到懒惰的隐式 val,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104937/

相关文章:

database - 如何使用 actor 进行数据库访问和 DDD?

scala - 集合中通用多态数据的上下文边界

scala - 拆分 Monix Observable

scala - 无法使用 IntelliJ 在本地连接到 hdfs kerberized 集群

scala 隐式导致 StackOverflowError

scala - 使用 shapeless.Generic 时,如何避免错误 'super constructor cannot be passed a self reference unless parameter is declared by-name' ?

java - 用 Scala 隐式包装的 Java 接口(interface)实现的工厂方法?

scala - 类型边界意外更改 Scala 隐式参数解析的优先级

sql-server - SQL Server 如何决定隐式日期时间转换的格式?

构造函数的 Scala 元组解包