Here's a simplification of the classes I have:
trait RequiredThings {
val requiredThings: Seq[String]
}
class SimpleCalculator with RequiredThings {
val requiredThings = List("a", "b")
}
class ComplicatedCalculator extends SimpleCalculator with RequiredThings {
self: SimpleCalculator =>
override val requiredThings:List[String] = List("c") ::: self.requiredThings
}
In this version, I'm using a self-type annotation, but I'm not completely positive that's the way to go. I think I could probably get it to work by converting requiredThings
to a method throughout, but I'd like to try it as a field.
Final solution:
trait RequiredThings {
def requiredThings: Seq[String]
}
class SimpleCalculator with RequiredThings {
def requiredThings = List("a", "b")
}
class ComplicatedCalculator extends SimpleCalculator with RequiredThings {
override def requiredThings:List[String] = List("c") ::: super.requiredThings
}
In scala, you must use either override keyword or override annotation to override methods from parent class.
Scala overriding method provides your own implementation of it. When a class inherits from another, it may want to modify the definition for a method of the superclass or provide a new version of it. This is the concept of Scala method overriding and we use the 'override' modifier to implement this.
The rules for the field overriding are as follows: The one of the foremost rule is that we must utilize the keyword override or override notation while overriding the fields of the super-class in the sub-classes otherwise the compiler will throw an error and will terminate the execution of the program.
When overriding a concrete member or implementing an abstract one, use the override keyword.
Yes, super calls to methods "inherited" through the self-type are not yet implemented. This will change (somewhat) soon. In the meantime, you should use inheritance instead.
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