

Or by omitting the this receiver: // same extension function, // but using the implicit receiver (no "this") fun String. We can define trimSpaces as an extension to the String class like this: // extension function fun String. Instead of this dull regular function: // regular function fun trimSpaces (s: String): String = This is exactly what extension functions let you do! Let's implement the example above. Wouldn't this be more readable like this? imSpaces().capitalize()


Kotlin is fun - Function types, lambdas, and higher-order functionsĬonsider the following piece of code: capitalize(trimSpaces(myString)) 🔖 I created this Table of Contents using BitDownToc. The magic of Kotlin's standard library explained This is an awesome feature and will shed light on the Kotlin standard library. This mechanism is called an extension function. Such functions can be called in the usual way as if they were methods of the original class. This is done via special declarations called extensions.įor example, it is possible to write new functions for a class or an interface from a third-party library that you can't modify, or from built-in types. Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator.
