How to access an overridden data member in Scala?

How to call an overridden data item in Scala? Here is an example from a worksheet - I would like to do something like:

trait HasWings {
  def fly() = println("I'm flying!")
  val wingType = "Thin"
}

class Bee extends HasWings {
  override def fly() = {
    println("Buzzzz! Also... ")
    super.fly()  // we can do this...
  }

  override val wingType = "Translucent and " + super.wingType  // ...but not this!
}

val bumble = new Bee()

bumble.fly()
println(s"${bumble.wingType}")

But I get an error super may not be used on value wingType. How can I override a data member while still accessing it? There are workarounds, for example:

  • Do not override superclass value
  • Declaring a superclass value as a method

But I am wondering if I can get an override and access to the data member in the superclass.

Thanks!

+4
source share
2 answers

, scala super a val. , , def, val. def

trait HasWings {
  def wingType0: String = "Thin"
  val wingType = wingType0
}

class Bee extends HasWings {
  override def wingType0 = "Translucent and " + super.wingType0
}
+6

, .

+2

Source: https://habr.com/ru/post/1607389/


All Articles