Automaticly limit max value

Is it possible to make an integer unable to have it’s value max at 10 using delegates ?
I’m not sure how delegates works but is it possible to make it look like

var foo: Int by Limiter(2, 10)

so that foo’s value is 2 when initialized, and it can’t exceed 10

1 Like

I know about vetoable but I want something less verbose

Do you need a library with that limiter?

Well you could just declare a function that returns a vetoable. Same as lazy returns the right delegate for lazy initialization.

fun limiter(start: Int, max: Int) = Delegates.vetoable(start) { _, _, newValue -> newValue <= max }

Actually, here is the implementation that did just what I wanted

class IntervalDelegate(
    var value: Int,
    val minValue: Int,
    val maxValue: Int
) : ReadWriteProperty<Any?, Int> {

override fun getValue(thisRef: Any?, property: KProperty<*>) = value

override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
    this.value = value.coerceIn(minValue, maxValue)
}
}
1 Like