How do extension functions work?

Just curious: How do extension functions work in Kotlin? This is not about the syntax but about what is going on behind the scenes. What are the mechanics to add methods to arbitrary classes that can even be final (e.g. String)?

One more thing that is about syntax: how does Kotlin know which classes declare extension functions for other classes? After all, I could be loading a class that contains extension functions for String.class through a URLClassLoader. Is there a resolution order for finding extension functions and to disambiguate if there are two classes trying to add the same extension function?

3 Likes

As the docs say: "Extension functions are resolved statically", i.e. they are normal static methods bearing no connection with the class they are extending, other than taking an instance of this class as a parameters. http://confluence.jetbrains.com/display/Kotlin/Extension+functions

Answering your second queations: extensions must be in scope, i.e. if they are not visible statically, you have to import them.

1 Like

So, this is just a trick the Kotlin compiler is playing without actually modifying the targeted class? There's no way to address the extension function through reflection or from Java code?

1 Like

The target classes are not modified. Extensions are visible from Java reflection as static methods in the classes they are defined in (.i.e. in package-classes for top-level extension functions).

1 Like

As abreslav said above, nothing changed to the target class on which you add extension functions. The complier will generate those extension functions as “normal static final java methods”. You can see this after complied your kotlin code into bytecode. So your invoke on an extension function of a certain target class, under the hood, you invoke a static final java method which has an instance of the target class as its first parameter in the method.