Search code examples
kotlinextension-function

How does a extension method work in Kotlin?


In Java you cannot extend a final class, but in Kotlin you can write extension method to such final classes. How did they make it work internally? I couldn't find any article that explained the inner workings of Kotlin Extension Methods.


Solution

  • In Java you cannot extend a final class, but in Kotlin you can write extension method to such final classes

    I think you are assuming extension methods used inheritance which is not. It is rather a static method disguised in kotlin syntactic sugar. For example look at the below simple extension method:

    String.removeSpace(): String {
        return this.replace(" ", "")
    }
    

    You can think it as equivalent to the following java code.

    static String removeSpace(String input) {
        return input.replace(" ", "")
    }
    

    What kotlin does here is it provides wrapper on top so that by using this you can get the instance of the caller. By combining that with Kotlin's capability of define function as first class citizen, you can write elegant thing like this:

    fun String.removeSpace() = this.replace(" ", "")