0
0
Kotlinprogramming~5 mins

Extensions resolved statically in Kotlin

Choose your learning style9 modes available
Introduction

Extensions in Kotlin add new functions to classes without changing them. They are resolved based on the type known at compile time, not the actual object type at runtime.

When you want to add a function to a class you cannot modify.
When you want to write cleaner code by calling new functions directly on objects.
When you want to provide utility functions for existing classes.
When you want to avoid inheritance but still extend functionality.
Syntax
Kotlin
fun ClassName.newFunction() {
    // function body
}
Extension functions look like normal functions but are called on an instance of the class.
They do not actually modify the class or its instances.
Examples
Adds an exclamation mark to a String.
Kotlin
fun String.addExclamation() = this + "!"
Checks if an integer is even.
Kotlin
fun Int.isEven() = this % 2 == 0
Shows that extension functions are resolved by the declared type, not the actual object type.
Kotlin
open class Base
class Derived : Base()

fun Base.foo() = "Base"
fun Derived.foo() = "Derived"

fun printFoo(b: Base) {
    println(b.foo())
}
Sample Program

Even though base holds a Derived object, the extension function called is for Base because extensions are resolved statically by the variable's declared type.

Kotlin
open class Base
class Derived : Base()

fun Base.foo() = "Base"
fun Derived.foo() = "Derived"

fun main() {
    val base: Base = Derived()
    println(base.foo())
}
OutputSuccess
Important Notes

Extension functions do not override member functions.

If a member function and an extension function have the same signature, the member function is called.

Extensions are resolved at compile time based on the variable's declared type, not the runtime type.

Summary

Extensions add functions to classes without changing them.

They are resolved statically by the declared type, not dynamically by the actual object.

This means the extension function called depends on the variable type, not the instance type.