Function0的标量堆栈修改

问题描述 投票:1回答:1

我只是在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

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

scala stack-overflow traits
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.