gpt4 book ai didi

带有惰性 val 的 Scala 线性化,为什么无限递归?

转载 作者:行者123 更新时间:2023-12-01 00:58:56 26 4
gpt4 key购买 nike

尝试实现一个利用 Scala 线性化优势的结构时,我们发现了一些我们不理解的行为。

如果将覆盖字段设置为 def,一切都会按预期进行,如果我们将其设置为 lazy val,它会因无限递归循环而崩溃.

带有 defs 的代码:

trait T {
def fields: List[Int] = Nil
}

trait A extends T {
override def fields = 1 :: super.fields
}

trait B extends T {
override def fields = 2 :: super.fields
}

val x = new B with A

println(x.fields)

带有惰性值的代码:
trait T {
def fields: List[Int] = Nil
}

trait A extends T {
override lazy val fields = 1 :: super.fields
}

trait B extends T {
override lazy val fields = 2 :: super.fields
}

val x = new B with A

println(x.fields)

为什么会发生这种情况?

最佳答案

我认为这与 https://issues.scala-lang.org/browse/SI-3167 的情况相同

Scala compiler bug: Stackable traits and lazy vals causing StackoverflowException


trait Thing { def name: String }
trait Thing1 extends Thing { override lazy val name = "One" }
trait Thing2 extends Thing { abstract override lazy val name = super.name }
val t = new Thing with Thing1 with Thing2
t.name

结果 java.lang.StackOverflowError .

你可以让它更相似。
trait Thing { def name: String = "" }
trait Thing1 extends Thing { override lazy val name = "One" }
trait Thing2 extends Thing { override lazy val name = super.name }
val t = new Thing with Thing1 with Thing2
t.name

这也会导致 java.lang.StackOverflowError .

无论如何,这个错误修复他妈的被推迟了。
Added the Fix Version 'Scala 2.11.3'
Removed the Fix Version 'Scala 2.11.2'

Added the Fix Version 'Scala 2.11.2'
Removed the Fix Version 'Scala 2.11.1'

Added the Fix Version 'Scala 2.11.1-RC1'
Removed the Fix Version '2.11.1-RC1'

Added the Fix Version '2.11.1-RC1'
Removed the Fix Version 'Scala 2.11.0-RC1'

Added the Fix Version 'Scala 2.11.0-RC1'
Removed the Fix Version 'Scala 2.11.0-M8'

Added the Fix Version 'Scala 2.11.0-M8'
Removed the Fix Version 'Scala 2.11.0-M7'

Added the Fix Version 'Scala 2.11.0-M6'
Removed the Fix Version 'Scala 2.11.0-M4'

Added the Fix Version 'Scala 2.11.0-M4'
Removed the Fix Version 'Scala 2.11.0-M3'

Added the Fix Version 'Scala 2.11.0-M3'
Removed the Fix Version 'Scala 2.11.0-M2'

...

随着 2010 年报告的问题。

我建议不要使用 lazy val s 调用 super在可堆叠的特征中。

关于带有惰性 val 的 Scala 线性化,为什么无限递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25268314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com