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:
But I'm curious if I can have my override and my superclass data member access.
Thanks!
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
}
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