Mike Williamson
Mike Williamson

Reputation: 3178

Why is this expression considered immutable, and therefore can be defined using `val`?

In a training video, I saw a nice, concise "trick" to demonstrate accessors that looked like this:

val alive
    get() = health > 0

This provided a nice, easy way to provide a "getter and setter" all in one, where the "setter" is really just a derived value. I understand all that.

But I guess I don't quite understand what val means, and therefore "immutable" means. I was imagining a location in memory that was unchangeable. Is that really what's happening here? Maybe the location in memory actually points to an expression that is expecting a value (health), and so therefore this is, in effect, immutable.

Upvotes: 1

Views: 62

Answers (1)

Joffrey
Joffrey

Reputation: 37700

You simply need to think of val as read-only rather than immutable.

Also, please note that you're not declaring the expression as val, but the property.

Declaring a val property will only generate a getter for the property, not a setter. In Java, you could have written the same "computed getter" (without a backing field, and without a setter):

public class Player {
    private int health = 100;

    public int getHealth() { 
        return health; 
    }

    public void setHealth(int health) { 
        this.health = health; 
    }

    public boolean isAlive() {
        return health > 0;
    }
}

I was imagining a location in memory that was unchangeable.

As you can see in the Java equivalent above, it's not even a location in memory (there is no backing field). Each time the property is accessed (internally using the generated getter), the expression health > 0 is evaluated again and may yield a different value than a previous access to the property.

Upvotes: 6

Related Questions