...

/

Calling Java from Kotlin

Calling Java from Kotlin

Calling code written in Java from within Kotlin .kt files and .kts scripts is straightforward for most part. Kotlin naturally integrates with Java, and we can use properties and methods without thinking twice—it almost always just works.

The Java code

To see this in action, and learn ways to work around occasional glitches you may run into, let’s write a Java class that we will then use from Kotlin.

Press + to interact
package com.agiledeveloper;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class JavaClass {
public int getZero() { return 0; }
public List<String> convertToUpper(List<String> names) {
return names.stream()
.map(String::toUpperCase)
.collect(toList());
}
public void suspend() {
System.out.println("suspending...");
}
public String when() {
return "Now!";
}
}

The class JavaClass has a getter method, a convertToUpper() method, a method named suspend(), and another method named when(). The purpose of the first two methods is to illustrate how Kotlin works well with Java. The last two methods will help to see how Kotlin deals with Java method names that conflict with keywords in Kotlin.

Running from the command line

In this example, the Kotlin code we’ll soon write will depend on Java code, but no Java code depends on Kotlin code. So we can straightaway compile the Java code using the ...