如何在 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}")
但是我得到了错误,
super may not be used on value wingType
. 如何在仍然访问它的同时覆盖数据成员? 有解决方法,例如:但是我很好奇我是否可以拥有我的覆盖和我的父类(super class)数据成员访问权限。
谢谢!
最佳答案
正如编译器告诉你的,scala 不允许使用 super
在 val
.
如果你需要这个,你可以重构你的代码以使用 def
用于初始化 val
.然后你可以覆盖 def
反而:
trait HasWings {
def wingType0: String = "Thin"
val wingType = wingType0
}
class Bee extends HasWings {
override def wingType0 = "Translucent and " + super.wingType0
}
关于scala - 如何访问 Scala 中被覆盖的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577993/