Sobes.tech
Junior — Middle

Is an extension function in Kotlin always static within its implementation?

sobes.tech AI

Answer from AI

Yes, in Kotlin, extension functions are implemented as static methods at the JVM bytecode level. Although they appear syntactically as methods added to existing classes, they do not actually modify the class and do not have access to private members.

This means that within the implementation of an extension function, there is no reference to the class instance (this) in the usual sense of methods. Instead, the first parameter of the extension function is the object to which it is applied.

Example:

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

In bytecode, this will look like a static method accepting a String object as a parameter.

Therefore, extension functions in Kotlin are always static in their implementation, even though they look like instance methods.

Is an extension function in Kotlin always static… - sobes.tech