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