Assume the following example - when executed returns - "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()
}
}
Looking at what the compiler does - gives a better explanation of what is going on
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>();
()
}
}
}
Can please elaborate why this is the expected behavior?
Because that is how the Scala specification says it should work. 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).
Internally, Scala implementation which directs the JVM has to store the default parameter as a member of the declaring class, since the JVM doesn't directly support default arguments on methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With