Automaticly limit max value


#1

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


#2

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/vetoable.html


#3

I know about vetoable but I want something less verbose


#4

Do you need a library with that limiter?


#5

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 }

#6

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)
}
}