Functions with the JVM annotation

We can call the Kotlin function in Java by using the filename as a reference. We also need to add the kt keyword with the filename; for example, KotlinToJavakt. However, Kotlin makes it possible to assign different names to our file and function names. Create a new class named CallKotlinUtil.kt and add the following code:

@file:JvmName("KotlinUtil")
package Chapter08.CallKotlinFromJava

fun addition (a: Int, b : Int){

println("Result of $a + $b is ${a+b}")

}

Use the @file:JvmName("KotlinUtil") annotation at the beginning of the file. Now we can call the addition function by using KotlinUtil.addition instead of CallKotlinUtilkt.addition. See the following example:

public static void main(String args[]) {
KotlinUtil.addition(4,4);
}

This is a much better and cleaner approach. We can now specify the Kotlin filename for the Java class to use as a reference. Kotlin also makes it possible to specify the name of the Kotlin function for Java. Create an addition function in the Kotlin file and add the @JvmName annotation with a new function name, as follows:

@file:JvmName("KotlinUtil")
package CallKotlinFromJavaPackage

@JvmName
("addDouble")
fun addition (a: Double, b : Double){
println("Result of $a + $b is ${a+b}")
}

Now we can call the addition function by using addDouble. See the following example:

public static void main(String args[]) {
KotlinUtil.addDouble(5.0, 5.0);
}
..................Content has been hidden....................

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