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.
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.
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…)