I'm confused by the following:
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
}
I was expecting:
mystring
why don't I see this?
But I get:
mystring
mystring
In java if you override, or 'shadow' a variable in a super class, the super class has its own variables. But here, even though I think I'm explicitly initializing the parent with a different string, the parent gets set to the same value as the subclass?
In scala
val
is similar to getter method in java
. You can even override def
with val
.
If you need something similar to field from java
you should use 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With