gpt4 book ai didi

Scala : Why can't we do super. val?

转载 作者:行者123 更新时间:2023-12-04 14:39:43 26 4
gpt4 key购买 nike

我正在从 JavaTpoint 练习这段代码,用于在 Scala 中学习继承。但是我无法从值初始化为零的 Vehicle 类访问成员 Bike 。我尝试通过父类(super class)型引用,但它仍然显示覆盖的值。为什么它不允许访问父类(super class)字段并指向覆盖的子类字段(速度)。这是代码和输出。
提前致谢。

class Vehicle {
val speed = 0
println("In vehicle constructor " +speed)
def run() {
println(s"vehicle is running at $speed")
}
}

class Bike extends Vehicle {
override val speed = 100
override def run() {
super.run()
println(s"Bike is running at $speed km/hr")
}
}

object MainObject3 {
def main(args:Array[String]) {
var b = new Bike()
b.run()
var v = new Vehicle()
v.run()
var ve:Vehicle=new Bike()
println("SuperType reference" + ve.speed)
ve.run()
}
}

How do I get the result using instance of Bike.

最佳答案

类似问题的答案在这里overriding-vals-in-scala ,或在这里 cannot-use-super-when-overriding-values说:Scala compiler does not allow to use super on a val
这是为什么?上面最后一个链接中的讨论指向:SI-899 .那里的第一条评论如下:it was changed so that traits could override vals to be more uniform with classes

关于Scala : Why can't we do super. val?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45935672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com