Search code examples
kotlinkotlin-extension

Modify "this" in extension function


I want to write extension function that modifies "this", for example:

var a = false
a.toggle() // now a contains false

or

var a = 1
a.increment() // now a contains 2

Is it possible in Kotlin?

I can create extension function that returns modified value, but leaves "this" unmodified, but I want even more convenience! It looks like Swift can do that.


Solution

  • References to variables aren't supported yet but you can create extension functions to use with property references:

    fun KMutableProperty0<Boolean>.not() = set(get().not())
    fun KMutableProperty0<Int>.inc() = set(get().inc())
    
    var a = false
    var b = 1
    
    fun main(vararg args: String) {
        ::a.not()
        // now `a` contains `true`
        ::b.inc()
        // now `b` contains `2`
    }
    

    Or if you'd rather the extension functions return the new value along with setting it:

    fun KMutableProperty0<Boolean>.not(): Boolean = get().not().apply(setter)
    fun KMutableProperty0<Int>.inc(): Int = get().inc().apply(setter)