如何在Scala中调用被覆盖的数据成员?这是工作表中的一个例子 - 我想做的事情如下:
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}")
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误super may not be used on value wingType.如何在仍然可以访问数据成员的同时覆盖数据成员?有一些解决方法,例如:
但我很好奇我是否可以使用我的覆盖和我的超类数据成员访问.
谢谢!
正如编译器告诉你的那样,scala不允许super在aa 上使用val.如果需要,可以重构代码以使用def用于初始化代码的代码val.然后你可以改写def:
trait HasWings {
def wingType0: String = "Thin"
val wingType = wingType0
}
class Bee extends HasWings {
override def wingType0 = "Translucent and " + super.wingType0
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
738 次 |
| 最近记录: |