我只是在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()
我希望输出类似于modified base
。相反,我得到了modified modified modified...
导致了StackOverflowError
[有趣的是,仅在Function0 [Unit]中才发生。 Function [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