Why is a var with private set not highlighted as val?

When creating a var with private set, like this

var foo: Bar
    private set

Why when the variable is used outside of the class is it highlighted as a var (i.e. with a underscore)? To classes outside of the private scope it’s just like a normal val and it should be highlighted as such. Am I missing something or is this just a not yet implemented feature?

1 Like

But it’s not a normal val. A val cannot be changed no matter what (except with reflection, I guess). A var with private set on the other hand can be changed by a public method that calls the private setter. Highlighting it as val would, therefore, be confusing to the developers, at least in my opinion.

That is not right. A val can be changed. Just not directly. val only means that the value is readonly. You could still have a val which changes on some other condition. Therefor a val and a var with private set should behave the same to the outside.

1 Like

Correct me if I’m wrong, but you can do this:

class Bar
class Baz {
    var foo: Bar = Bar()
        private set

    fun mutate() {
        foo = Bar()
    }

    fun mutate(bar: Bar) {
        foo = bar
    }
}

but this should not work:

class Baz2 {
    val foo: Bar = Bar()

    fun mutate() {
        foo = Bar()
    }

    fun mutate(bar: Bar) {
        foo = bar
    }
}

so you cannot treat those two constructs the same way.

Your right about your example but you could also do this

class Bar {
    private var backingField: Foo = Foo()

    val field: Foo
        get() = backingField

    fun mutate(foo: Foo = Foo()){
        backingField = foo
    }
}

Thereby changing the value of field

1 Like

OK, I understand your point now.

However, it occurs to me that if the IDE marked var with privat set as val one could also argue it should also mark val as var if it is used the way you did on your example. Do we really want to waste time waiting for it to do that?

Actually I don’t quite now what you mean with marked as var or val, can you give me an example of it (screenshot)?

I think the problem is that a lot of people think of val equivalent to immutability, which it is not. val only means that a value is readonly.

1 Like

By ‘marked’ I mean ‘highlighted’ as in the original question. Sorry for the confusion.

I agree. I keep forgetting about that fact myself :smiley:

1 Like