Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an overridden data member in Scala?

How do I call an overridden data member in Scala? Here's an example from a worksheet -- I'd 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 the error, super may not be used on value wingType. How can I override the data member while still getting access to it? There are workarounds, like:

  1. Not overriding the superclass value
  2. Declaring the superclass value as a method

But I'm curious if I can have my override and my superclass data member access.

Thanks!

like image 385
einnocent Avatar asked Mar 15 '23 19:03

einnocent


1 Answers

As the compiler tells you, scala does not allow to use super on a a val. If you need this, you can refactor your code to use a def that is used to initialize the val. Then you can override the def instead:

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

class Bee extends HasWings {
  override def wingType0 = "Translucent and " + super.wingType0
}
like image 67
Régis Jean-Gilles Avatar answered Mar 18 '23 03:03

Régis Jean-Gilles