Ji Sungbin
Ji Sungbin

Reputation: 1301

Val-property cannot override var-property

I thought var could be overridden as val with the only getter because it has both getter and setter. But this is impossible.

And, if override val that only has getter with var that has setter, no error occurs. I don't know how this is possible.

Why does it work this way?

Upvotes: 1

Views: 752

Answers (3)

broot
broot

Reputation: 28342

Your second example (overriding val with var) is similar to this pseudocode:

open class Test {
    fun getA()
}

class Main : Test() {
    fun setA()
}

Main subclass just adds a new method, there is no reason why it would be not possible. Your first example (overriding var with val) would be similar to:

open class Test {
    fun getA()
    fun setA()
}

class Main : Test() {
    // remove setA() function
}

As you probably know, it is not possible to remove methods in subclasses, so it is not possible to override var with val.

Upvotes: 7

Vojin Purić
Vojin Purić

Reputation: 2376

First the reason you can override val with a var is that it is equivalent to adding a setter while in the superclass there was only a getter. And this is rather important in implementing some patterns.

Secondly if you are opening a variable that means that you want to make it changeable in a subblass. Don't forget that val means read-only not immutable. And if you want to keep setter private you still can when you override

override var a = 1
    private set

Upvotes: 1

D. Kupra
D. Kupra

Reputation: 373

Because client classes will attempt to interact with Main as if it were a Test. That's the point of making Test open, so that clients will interact with its children with the expectation that those children will behave like Test and accept all of the same method calls and variable reassignments.

If Test makes a contract with all of its client users that they are allowed to change a, then Main is breaking that contract if it makes a unchangeable.

Upvotes: 0

Related Questions