gpt4 book ai didi

scala - 使用默认参数覆盖特征方法

转载 作者:行者123 更新时间:2023-12-03 04:02:35 28 4
gpt4 key购买 nike

假设以下示例 - 执行时返回 - “fatherfather”

trait Action {
def doSomething(s:String = "father") = s
}

class RevokeAction extends Action{
override def doSomething(s:String) = {
s + s
}
}

object HelloWorld {
def main(args: Array[String]): Unit = {
val revokeAction = new RevokeAction()
revokeAction.doSomething()
}
}

查看编译器的作用 - 更好地解释正在发生的事情

package <empty> {
abstract trait Action extends Object {
def doSomething(s: String): String = s;
<synthetic> def doSomething$default$1(): String = "father";
def /*Action*/$init$(): Unit = {
()
}
};
class RevokeAction extends Object with Action {
<synthetic> def doSomething$default$1(): String = RevokeAction.super.doSomething$default$1();
override def doSomething(s: String): String = s.+(s);
def <init>(): RevokeAction = {
RevokeAction.super.<init>();
RevokeAction.super./*Action*/$init$();
()
}
};
object HelloWorld extends Object {
def main(args: Array[String]): Unit = {
val revokeAction: RevokeAction = new RevokeAction();
{
revokeAction.doSomething(revokeAction.doSomething$default$1());
()
}
};
def <init>(): HelloWorld.type = {
HelloWorld.super.<init>();
()
}
}
}

能否详细说明为什么这是预期的行为?

最佳答案

因为 Scala 规范规定它应该这样工作。 Section 5.1.4 (Overriding) :

An overriding method inherits all default arguments from the definition in the superclass. By specifying default arguments in the overriding method it is possible to add new defaults (if the corresponding parameter in the superclass does not have a default) or to override the defaults of the superclass (otherwise).

在内部,指导 JVM 的 Scala 实现必须将默认参数存储为声明类的成员,因为 JVM doesn't directly support default arguments on methods .

关于scala - 使用默认参数覆盖特征方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44149283/

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