Interoperability

As we have seen, Kotlin is fully interoperable with Java so that you can write Java and Kotlin functions altogether in the same project and call them from each other. Let's understand how that magic happens. Before that, let's look at how things happen behind the scenes.

For example, you wrote a Kotlin function in the CheckOperability.kt file as follows: 

fun greeting(name: String){
print(" Hello $name !!!")
}

This code will be compiled by the Kotlin compiler and converted into byte code. The generated Java class file will be as follows:

public final class CheckInterOperabilityKt
{
public static final void greeting(@NotNull String name)
{
//Some code for null type check added by Kotlin at this place.
String str = " Hello " + name + " !!!";System.out.print(str);
}
}

As you can see, Kotlin converts the .kt file (CheckInterOperabilityKt.class) into a corresponding Java class. The greeting() function defined in Kotlin is also converted to a Java function. By default, all functions in Kotlin are static. Also, Kotlin is not forcing you to define a void in case there is no-return value. (Kotlin has Unit in place of void actually.) While converting, it will add void along with a static keyword to the function. 

We will now see how we can call the Java code from Kotlin, and vice versa.

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

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