Often, we work with classes and APIs we do not control. This can mean we are required to write code based on the style or requirements of those external parties. Extension functions provide a means of extending or modifying code we do not control. For example, we could write an extension function to determine whether or not String equals "Kotlin".
In the following snippet, we've written an isKotlin() function. This function is an extension function of the String type. This means that it's only available to instances of the String receiver type. Note that the function name is defined by first specifying the receiver type, in this case String, and then adding . and then the function name:
fun String.isKotlin() = this == "Kotlin"
Once the extension function is written, it can be called on instances of the receiver type as if it existed on that type. In this case, isKotlin() can be called on any String variable or literal:
fun main(args: Array<String>) {
"some string".isKotlin()
}
Extension functions are one of the most popular and powerful features of Kotlin. They enable us to extend APIs and classes we don't control, and can even help organize and clean up our own code. Extension functions are a great way to encapsulate helper functions and are a powerful tool in building custom DSLs, as we'll see in Chapter 11, Building Your Own Tools – Domain-Specific Languages (DSLs).
As we've seen in this section, Kotlin functions provide a great deal of functionality and really do empower us to rethink how we write our code.