Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 630
Dmitry Ryadnenko Avatar asked Oct 12 '16 16:10

Dmitry Ryadnenko


People also ask

What is the extension of function?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.

How do you call a function with an extension?

The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call. The swap(0,2) function pass the index value of list inside MutableList<Int>.

What is the receiver in the extension function?

An instance of a class in which the extension is declared is called a dispatch receiver, and an instance of the receiver type of the extension method is called an extension receiver.

What is true about extension functions in Kotlin?

The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions.


1 Answers

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)
like image 193
mfulton26 Avatar answered Feb 22 '23 09:02

mfulton26