Extension functions

Definitively, one of the best features of Kotlin is extension functions. Extension functions let you modify existing types with new functions:

fun String.sendToConsole() = println(this)

fun main(args: Array<String>) {
"Hello world! (from an extension function)".sendToConsole()
}

To add an extension function to an existing type, you must write the function's name next to the type's name, joined by a dot (.).

In our example, we add an extension function (sendToConsole()) to the String type. Inside the function's body, this refers the instance of String type (in this extension function, string is the receiver type).

Apart from the dot (.) and this, extension functions have the same syntax rules and features as a normal function. Indeed, behind the scenes, an extension function is a normal function whose first parameter is a value of the receiver type. So, our sendToConsole() extension function is equivalent to the next code:

fun sendToConsole(string: String) = println(string)

sendToConsole("Hello world! (from a normal function)")

So, in reality, we aren't modifying a type with new functions. Extension functions are a very elegant way to write utility functions, easy to write, very fun to use, and nice to read—a win-win. This also means that extension functions have one restriction—they can't access private members of this, in contrast with a proper member function that can access everything inside the instance:

class Human(private val name: String)

fun Human.speak(): String = "${this.name} makes a noise" //Cannot access 'name': it is private in 'Human'

Invoking an extension function is the same as a normal function—with an instance of the receiver type (that will be referenced as this inside the extension), invoke the function by name. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.71