Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
Prabesh Avatar asked Dec 17 '22 12:12

Prabesh


1 Answers

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(" ", "")
like image 71
stinepike Avatar answered Jan 02 '23 10:01

stinepike