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!
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
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