Search⌘ K
AI Features

Extension Functions

Explore Kotlin's extension functions to extend classes with new behavior as if they were class members. Understand how to declare extensions using receiver types, how to use this keyword, and differentiate extension functions from member functions. Gain the ability to write cleaner, more expressive Kotlin code by leveraging extension functions and properties.

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:

Kotlin 1.5
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:

Kotlin 1.5
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’ the Int class itself ...