我对以下内容感到困惑:
class A(val s: String) {
def supershow {
println(s)
}
}
class B(override val s: String) extends A("why don't I see this?"){
def show {
println(s)
}
def showSuper {
super.supershow
}
}
object A extends App {
val b = new B("mystring")
b.show
b.showSuper
}
Run Code Online (Sandbox Code Playgroud)
我在期待:
mystring
why don't I see this?
Run Code Online (Sandbox Code Playgroud)
但我得到:
mystring
mystring
Run Code Online (Sandbox Code Playgroud)
在java中,如果你覆盖超级类中的变量或"影子"变量,那么超类就有自己的变量.但是在这里,即使我认为我使用不同的字符串显式初始化父级,父级也会设置为与子类相同的值?
In scala val类似于getter方法java.你甚至可以覆盖def有val.
如果您需要类似于字段的东西,java您应该使用private[this] val:
class A(private[this] val s: String) {
def superShow() = println(s)
}
class B(private[this] val s: String) extends A("why don't I see this?") {
def show() = println(s)
}
val b = new B("message")
b.show
// message
b.superShow()
// why don't I see this?
Run Code Online (Sandbox Code Playgroud)