Etam
Etam

Reputation: 4673

Inherited variable doesn't like new values

Could someone explain me why:

abstract class Super(var title: String)

class Sub(title: String) extends Super(title) {
    def test = println(title)
}

val s = new Sub("a")
s.test
s.title = "b"
s.test

prints:

a
a

instead of:

a
b

?

Upvotes: 0

Views: 58

Answers (1)

Arseniy Zhizhelev
Arseniy Zhizhelev

Reputation: 2401

It's easy. You simply refers to constructor param, not the inherited variable. You may either rename constructor param, or refer to the var with this. prefix

class Sub(titleP: String) extends Super(titleP) {
    def test = println(title)
}

Upvotes: 2

Related Questions