Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is parameter's default value still valid in sub class?

I have following code snippet,

trait DefaultValueInheritance {
  def print(str: String = "abc")
}

class MyDefaultValueInheritance extends DefaultValueInheritance {
  //Didn't provide default value in the sub class
  override  def print(str: String): Unit = {
    println(str)
  }
}

object MyDefaultValueInheritance {
  def main(args: Array[String]): Unit = {
    val a = new MyDefaultValueInheritance
    a.print()
  }
}

In the trait, DefaultValueInheritance, I define a method print, with default value for the argument: str.

In the sub class, when I override the print method, I didn't provide the default value for the str parameter,

I am still able to call a.print(), looks the default value still valid, I don't know why, thanks!

like image 593
Tom Avatar asked Dec 14 '22 09:12

Tom


1 Answers

Yes, default parameters are inherited automatically by subclasses. In invoking a.print(), "abc" is passed as the str parameter.

See section on overriding: https://docs.scala-lang.org/sips/named-and-default-arguments.html

like image 61
Nicholas Weston Avatar answered Jan 12 '23 15:01

Nicholas Weston