Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding val in scala

Tags:

scala

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?

like image 431
Bruce Avatar asked Jan 11 '23 22:01

Bruce


1 Answers

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?
like image 169
senia Avatar answered Jan 17 '23 15:01

senia