In Scala, is it possible to override a specific field containing a list and add something to it in a subclass?

Here's a simplification of classes I:

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 use self-tuning annotation, but I'm not quite sure which way to go. I think I could make it work by converting requiredThingsto a method, but I would like to try it as a field.

Final decision:

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
}
+5
source share
3 answers

Yes, super-calls to methods "inherited" via self-type have not yet been implemented. Soon it will change. In the meantime, you should use inheritance instead.

+7
source

Funny, yesterday I went to the same question.

, ( ), .

:

class A { def foo = "a" }
trait B { self: A => override def foo = self.foo + "b" }

( : super.foo, B ScalaObject, A)

, .

class A { def foo = "a"; def fooA = A.this.foo }
trait B { this: A => override def foo = fooA + "b" }

, , .

+4

It makes sense to have requiredThingsboth defat least in trait- it will give you more flexibility

+3
source

All Articles