Extension functions

In Java, it's common to define helper classes/methods that all act on a common type. An example of this might be a StringUtils class that contains a number of helper methods that all act on String. In Kotlin, we could define top-level functions for this that might all take a String parameter, but we could also solve this with extension functions.

Let's first imagine a StringHelpers class in Java:

public class StringHelpers {
public static void log(String msg) {
System.out.println("log: " + msg);
}
}

We could call this from both Java and Kotlin by passing a string into each invocation. With extension functions, we can define a function that, from Kotlin, will appear to be a method on the String type itself, and, from Java, will not require the enclosing class:

// extension function on String
fun
String.log() {
println("log: $this")
}

From Kotlin, we can call this function like this:

"message to log".log()

It will be treated like any other method in the receiver class.

From Java, we can still use this function like we would any other top-level function, but the first parameter will be the receiver type. In this case, the receiver is String, so we pass the message into the function like any other parameter:

HelpersKt.log("message to log");

This ensures that we can make use of our extension functions from both Java and Kotlin.