...

/

Extension Functions

Extension Functions

Learn about the concept of extension functions in Kotlin.

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:

Press + to interact
fun squared(i: Int) : Int {
return i * i
}
fun main() {
println(squared(2))
}

Thanks to Kotlin’s expression bodies, we can write it in an even shorter way:

Press + to interact
fun squared(i: Int) = i * i
fun main() {
println(squared(2))
}

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