Extension functions

The extension functions feature of Kotlin doesn't relate to functional programming, but it's better to explain this concept before moving forward. This feature allows us to extend a class or type with a new functionality, without using inheritance or any software design patterns, such as decorators.

In object-oriented programming, a decorator is a design pattern that allows us to add a behavior to an object dynamically, without affecting other objects from the same class.

In the following code snippet, the extension function is added to the functionality of the A class:

fun A.extension() {
println("Extension")
}

As you can see, it's easy to use this feature. We just need to specify a class name and declare a function name after the dot. Now, we can invoke the extension function as usual:

fun testExtension() {
A().extension()
}

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

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