Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding trait method with default parameter

Tags:

scala

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?

like image 243
Amit Paz Avatar asked Dec 24 '22 17:12

Amit Paz


1 Answers

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.

like image 147
Yuval Itzchakov Avatar answered Dec 26 '22 05:12

Yuval Itzchakov