Extension Functions in Kotlin

Alexander Portillo
1 min readApr 8, 2022

Extension functions make our code look more readable and clean. Kotlin allows us to extend the functionality of a class without having to inherit from the class. I will be showing you how to create an extension function and why you should start using them as you code.

We will be creating an extension function that will check if an Int is even and return true or false. This is the layout of an extension function.

fun <class_name>.<extention_function>()

In this case, Int is the class name and isEven is your extension function. You can call the extension function whatever you like. The “this” in your extension function refers to the Int.

fun Int.isEven(): Boolean {
return when (this % 2) {
0 -> true
else -> false
}
}

val number = 8
println("${number.isEven()}")

Notice how we can now call the function isEven() and our code looks much more readable. This is a simple extension function but imagine how much cleaner your code will look which is a much more complex one.

--

--