Skip to main content

Calling Java from Kotlin

Kotlin and Java are fully interoperable, which means that they can be used together in the same project. This offers a significant benefit as it helps to leverage the extensive libraries and frameworks of Java while enjoying the simplicity and conciseness of Kotlin. This article will focus on how to call Java from Kotlin.

Java and Kotlin Interoperability

Kotlin is completely interoperable with Java. This is possible because when Kotlin code is compiled, it is converted into bytecode, which is understood by the JVM (Java Virtual Machine). This means that you can call Java code directly from Kotlin and vice versa.

Calling Java Methods in Kotlin

Calling Java methods from Kotlin is straightforward. For instance, consider a Java class Employee with a method getName().

public class Employee {
private String name;

public Employee(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

In Kotlin, you can create an instance of Employee and call getName() method as shown below:

val employee = Employee("John Doe")
println(employee.name)

Notice that in Kotlin, you can use property access syntax to call the getter method. The Kotlin compiler automatically converts it to a getter method call.

Null Safety and Java Interoperability

Kotlin's null safety feature is one of its most notable features. By default, Kotlin types cannot be null. However, when calling Java methods, Kotlin relaxes this rule because Java doesn't have null safety built into its type system. When calling a Java method that returns a value, Kotlin treats the return type as a nullable type.

// Java
public String getName() {
return name;
}
val name = employee.name // name's type is String?

In the above example, name is of type String? in Kotlin even though getName() can't return null.

Java Setters in Kotlin

In Kotlin, you can use property access syntax to call Java setters. The Kotlin compiler automatically converts it to a setter method call.

public class Employee {
private String name;

public Employee(String name) {
this.name = name;
}

public void setName(String name) {
this.name = name;
}
}

In Kotlin, you can use the following code to call the Java setter method:

val employee = Employee("John Doe")
employee.name = "Jane Doe" // Calls setName method

Conclusion

Kotlin and Java interoperability is a powerful feature that lets you use Java libraries and frameworks in your Kotlin projects. This guide has shown you how to call Java methods from Kotlin, work with Java setters, and handle null safety when dealing with Java code. This feature makes it easier for Java developers to transition to Kotlin and allows you to gradually migrate your Java projects to Kotlin.