Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, can I override a concrete field containing a list and append something to it in the subclass?

Tags:

scala

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
}
like image 880
Edward Dale Avatar asked Mar 11 '10 09:03

Edward Dale


People also ask

How to override object in Scala?

In scala, you must use either override keyword or override annotation to override methods from parent class.

How to override methods in Scala?

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.

Which of the following are rules for the field overriding?

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 to use override Scala?

When overriding a concrete member or implementing an abstract one, use the override keyword.


1 Answers

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.

like image 183
lindydonna Avatar answered Jan 01 '23 07:01

lindydonna