我刚刚在 Scala 的堆栈修改中遇到了非常奇怪的行为。
让我们看一个例子:
class Base extends Function0[Unit] {
override def apply(): Unit = println("base")
}
trait Modification extends Function0[Unit] {
abstract override def apply(): Unit = { print("modified "); super.apply() }
}
val a = new Base with Modification
a.apply()
我希望输出类似于修改后的基础
。
相反,我得到了 modifiedmodifiedmodified...
导致 StackOverflowError
有趣的是,这种情况只发生在 Function0[Unit] 中。函数[String]工作正常:
class Base extends Function0[String] {
override def apply(): String = "base"
}
trait Modification extends Function0[String] {
abstract override def apply(): String = "modified " + super.apply()
}
val a = new Base with Modification
a.apply()
输出:
defined class Base
defined trait Modification
a: Base with Modification = <function0>
res0: String = modified base
有人可以解释一下这种行为吗?
最佳答案
看起来像一个错误,因为使用自定义 Function0
一切都按预期工作
trait Function0[+R] {
def apply(): R
}
class Base extends Function0[Unit] {
override def apply(): Unit = println("base")
}
trait Modification extends Function0[Unit] {
abstract override def apply(): Unit = { print("modified "); super.apply() }
}
val a = new Base with Modification
a.apply() // modified base
错误应在此处报告:https://github.com/scala/bug/issues
关于Function0 上的 Scala 堆栈修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58580830/