Is there a way to write an extension function that changes the value of an object?

In my case, I want to change the primitive - Boolean

I never liked the following type of code:

private var firstTime: Boolean = true ... if (firstTime) { // do something for the first time here firstTime = false } 

it would be nice if I had an extension function, for example:

 if (firstTime.checkAndUnset()) { // do something for the first time here } 

Is it possible?

+6
source share
2 answers

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() // First time 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) 
+6
source

Just create the following property

 private var firstTime: Boolean = true get() { return if (field) { //Note: field - is keyword in current context field = false true } else false } set(v) { field = v } 

And use is as simple as

 if (firstTime) { //It first time //firstTime is false now } 
+1
source

Source: https://habr.com/ru/post/1014912/


All Articles