首页 > 解决方案 > Function0 上的 Scala 堆栈修改

问题描述

我刚刚在 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] 中。功能 [字符串] 工作正常:

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

有人可以解释这种行为吗?

标签: scalastack-overflowtraits

解决方案


看起来像一个错误,因为自定义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


推荐阅读