Calling the Kotlin code from Java

Let's create a Kotlin function that simply does multiplication of two given numbers in the KotlinFile.kt file as follows:

fun multiply(a:Int, b:Int):Int{
print("Calling multiply function From Kotlin....")
return a * b
}

We want to call a Kotlin multiply() function into a Java class. As we know, the Kotlin compiler processes this file into a Java class, where it defines the multiply() method as a static method of the KotlinFileKt.class generated class file, so that it can be accessible with the KotlinFileKt.multiply() expression.

In case you wish to change the Java class file name from the Kotlin source, you need to define it as @file:JvmName("CustomKotlinFile") in the Kotlin file. In this case, the Kotlin compiler will generate the CustomKotlinFile.class file and the function can be accessed with the CustomKotlinFile.multiply() call. 

Let's first add the Java class and call the Kotlin function as follows: 

public class JavaFile {
public static void main(String args[]){
System.out.print(KotlinFileKt.multiply(3,4));
}
}

This is how the Kotlin function can be called from the Java class. Now let's see how to call a Java function from Kotlin.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.147.124