Sobes.tech
Junior — Middle

How is the extension function in Kotlin implemented and how does it work at a low level?

sobes.tech AI

Answer from AI

Extension functions in Kotlin do not actually add methods to a class at the bytecode level. They are implemented as static methods that take the receiver object as the first parameter.

For example, a function:

fun String.lastChar(): Char = this.get(this.length - 1)

Compiles roughly to a Java method:

public static char lastChar(String receiver) {
    return receiver.charAt(receiver.length() - 1);
}

That is, extension functions are syntactic sugar that allows calling such static methods as if they were methods of the object. This means extensions cannot access private members of the class, as they are not part of it.

Calling "abc".lastChar() compiles to a call to Extensions.lastChar("abc").

Thus, extensions are implemented at the JVM level as regular static methods with the first parameter being the object to which the extension is applied.