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.
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.
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>.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With