Accessing Kotlin extension functions from Java

Kotlin Mobile DevelopmentApps/Applications

In Kotlin, you can easily call another function by just importing the same in the current Kotlin file where your main function is running. Whatever the function we are declaring in a Kotlin file will be compiled into a static method by default, and it will be placed under the same package. The name of the newly created file will be renamed as the First letter capitalized and ".kt" extension replaced with the "Kt" suffix.

In this article, we will try to get an insight into how you can use Kotlin extension methods from a Java file.

Example

Let's create a Kotlin file and name it as "myExt.kt" and place the following code inside it.

Package com.extension

fun String.myFunc():String{
   return "Welcome to Kotlin Extension File"
}

Now we can easily access this extension in another Kotlin file by importing the same function, as shown below.

Package com.model

// Using this import statement,
// you can directly use this function
// in another Kotlin function.

import com.extension.myFunc

Now, our task is to use the function in the Java environment.

In the Java section, let's assume we have the following Java file and we want to use our previously generated extension method in the same.

Package com.service

// The newly created file that can be accessed via JVM
import com.extension.myExtKT

public class MyClass {
   public static void main(String args[]) {
      System.out.println(myExtKT.myFunc(););
   }
}

You can use your Kotlin Extension method directly using this newly static file create by the Kotlin compiler.

Output

Once the above piece of code is executed, it will generate the following output.

Welcome to Kotlin Extension File
raja
Updated on 23-Nov-2021 05:13:55

Advertisements