Call Kotlin Method from Java: Complete Guide

Calling a Kotlin method in Java is very straightforward, just follow the steps below:

  1. First and foremost, make sure that the Kotlin method is public by using the keyword “public” to modify the method in Kotlin code.
  2. Importing Kotlin classes: When importing Kotlin classes into Java code, the package path for Kotlin classes is kotlin.jvm.*.
  3. To instantiate a Kotlin class object in Java code, simply use the new keyword.
  4. 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.

bannerAds