Extension Functions
Learn about the concept of extension functions in Kotlin.
We'll cover the following...
Introduction
With the help of extension functions, classes can be extended, even if they are final, like String.
Extension functions allow us to declare functions outside a class, and yet their call looks like that of a method of that given class.
Example
Suppose that, in a project, it is necessary to calculate the square of an integer.
A suitable function for this is a quick write, as shown here:
Thanks to Kotlin’s expression bodies, we can write it in an even shorter way:
Since Kotlin allows functions on the package level, we could easily use this function now without any utility class. However, with Kotlin, we can do even better.
Using an extension function
By using an extension function corresponding to the example above, we can ‘teach’ the Int class itself ...