A possibly interesting development (var & val)

I was reading about var & val’s (“When an identifier holds data, you must decide whether it can be reassigned”) and it occurred to me it can be an interesting development regarding vars to include a way to limit how many times they can be assigned, meaning after “x” times they can’t be reassigned anymore.

Something like var<5> for instance, or var<x>.

What are use cases?

Also, val/var is mostly a compile-time construct and in most cases compiler can’t verify at the compile time how many times we access a variable. Property delegate could be a better fit here.

3 Likes

I don’t think I ever needed such a construct, and as broot pointed out, generally the best we could do is runtime checks. But this is already possible. The elegant solution would be indeed with a delegate, but even a crude custom setter would do:

var counter = 0
var x: String = ""
    set(value) {
        counter++
        if (counter > 3) error("oops")
        field = value
    }

Or you encapsulate the behavior in a class:

data class Box<T>(val initialValue: T, val maxTimes: Int) {
    private var counter = 0
    var value = initialValue
        private set

    fun set(t: T) {
        counter++
        if (counter >= maxTimes) error("oops")
        value = t
    }
}

No need to introduce a new syntax if you can create it yourself, if you really need it once in a blue moon. Also, that way you have much more control over the behavior (e.g. more complex conditions, which error to throw, logging…)

3 Likes

There are delegates for that if you really need it.

1 Like