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...