Call Kotlin Method from Java: Complete Guide
Calling a Kotlin method in Java is very straightforward, just follow the steps below:
- First and foremost, make sure that the Kotlin method is public by using the keyword “public” to modify the method in Kotlin code.
- Importing Kotlin classes: When importing Kotlin classes into Java code, the package path for Kotlin classes is kotlin.jvm.*.
- To instantiate a Kotlin class object in Java code, simply use the new keyword.
- Invoke Kotlin methods: Call Kotlin methods by instantiating a Kotlin class object, similar to calling Java methods.
Here is an example code:
Kotlin code:
class MyClass {
fun kotlinMethod() {
println("Hello from Kotlin method")
}
}
Java code:
import kotlin.jvm.functions.Function0;
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.kotlinMethod();
}
}
By following the above steps, you can call Kotlin functions in Java.