Jens Klingenberg

Kotlin: Extensions

Posted on September 25, 2017  •  2 minutes  • 285 words
Table of contents

Kotlin has a feature to extend classes with new functions and properties, that you are normally not able to extend, maybe because they are final classes. Or you don’t want to create a custom type just because you are missing one useful function.

How does it work

When you use Kotlin extensions, in your code it will look like the extended classes really contain the extension methods. But at compiling, the Kotlin compiler while convert your extensions to static Java methods.

In this example i will explain how to extend the String class with a function to reverse a string.

fun String.reverse() :String {
    return StringBuffer(this).reverse().toString();
}

To extend the class you just have to create a function that has the name of the class and the wanted method name (String.reverse()). This function can be in any of your kotlin classes.

In the body of the extension method you can get the object, on which the method is used on, with the keyword this. In this example i just pass the string into a StringBuffer to reverse it and then return it.

Call the extension function in Kotlin

fun main(args: Array<String>) {
     println("Hallo".reverse())
}

You can use the extension like any other function.

Call the extension function in Java

Let's say the extension function is inside the file Extension.kt To call the function within your Java Code, you have to use
 ExtensionKt.reverse("Hallo");

One alternative is to give the compiler an other name for the Extension.kt file.

@file:JvmName("StringUtils")

When you add the JvmName annotation to your extension class. You can then use this name to use the function.

System.out.println(StringUtils.reverse("hallo"));

Example Project

You can try the code yourself in browser on Try Kotlin

Reference

Kotlin extension documentation
Let's connect: