The solution that will work for properties is to write an extension function for mutable properties, and then use it with a reference to the property. This code works with Kotlin 1.1:
fun KMutableProperty0<Boolean>.checkAndUnset(): Boolean { val result = get() set(false) return result }
Using:
class MyClass { private var firstTime = true fun f() { if (this::firstTime.checkAndUnset()) { println("First time") } } } fun main(args: Array<String>) { val c = MyClass() cf()
(check out the runnable demo)
This, however, will not work for local variables (at least not in Kotlin 1.1).
In Kotlin 1.0.x, related called links are not yet available, and the above solution can be rewritten to this somewhat more awkward code:
fun <T> KMutableProperty1<T, Boolean>.checkAndUnset(receiver: T): Boolean { val result = get(receiver) set(receiver, false) return result }
MyClass::firstTime.checkAndUnset(this)
source share