如何在Scala中访问被覆盖的数据成员?
发布时间:2020-12-16 09:51:08 所属栏目:安全 来源:网络整理
导读:如何在 Scala中调用被覆盖的数据成员?这是工作表中的一个例子 – 我想做的事情如下: trait HasWings { def fly() = println("I'm flying!") val wingType = "Thin"}class Bee extends HasWings { override def fly() = { println("Buzzzz! Also... ") supe
如何在
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}") 但我得到错误,超级可能不会用于值wingType.如何在仍然可以访问数据成员的同时覆盖数据成员?有一些解决方法,例如: >不覆盖超类值 但我很好奇我是否可以使用我的覆盖和我的超类数据成员访问. 谢谢! 解决方法
正如编译器告诉你的那样,scala不允许在val上使用super.
如果需要,可以重构代码以使用用于初始化val的def.然后你可以改写def: trait HasWings { def wingType0: String = "Thin" val wingType = wingType0 } class Bee extends HasWings { override def wingType0 = "Translucent and " + super.wingType0 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |