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?


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.

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


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?


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).

Extention functions performances