W3cubDocs

/Kotlin

vetoable

inline fun <T> vetoable(
    initialValue: T, 
    crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean
): ReadWriteProperty<Any?, T>

Returns a property delegate for a read/write property that calls a specified callback function when changed, allowing the callback to veto the modification.

import kotlin.properties.Delegates

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
var max: Int by Delegates.vetoable(0) { property, oldValue, newValue ->
    newValue > oldValue
}

println(max) // 0

max = 10
println(max) // 10

max = 5
println(max) // 10
//sampleEnd
}
import kotlin.properties.Delegates

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
var max: Int by Delegates.vetoable(0) { property, oldValue, newValue ->
    if (newValue > oldValue) true else throw IllegalArgumentException("New value must be larger than old value.")
}

println(max) // 0

max = 10
println(max) // 10

// max = 5 // will fail with IllegalArgumentException
//sampleEnd
}

Parameters

initialValue - the initial value of the property.

onChange - the callback which is called before a change to the property value is attempted. The value of the property hasn't been changed yet, when this callback is invoked. If the callback returns true the value of the property is being set to the new value, and if the callback returns false the new value is discarded and the property remains its old value.

© 2010–2018 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/vetoable.html