Java Interoperability – Calling Java from Kotlin

09 Sep, 2021
Since Kotlin was developed keeping in mind the interoperability with Java. It makes it easier to use Java code from within itself. A Kotlin class or a function can refer to the Java classes and their methods in a simple way. 
The getters and setters of all the types defined within the Java class are represented as properties in the Kotlin. Hence, to access the getters and setters of a data member of a Java class, it must reference as a property within Kotlin.Java file declared as myjava.java  
Java
// Java classpublic class myjava {  private int value;  public int getValue(){       return value;  }  public void setValue(int value){       this.value = value;  }}
Kotlin file declared as mykotlin.kt  
Java
// Kotlin filefun main(){   val obj = myjava()   obj.value = 5 // This will call the setter function   println(obj.value) // This will call the getter function}
Output:  
5
 
Calling the Java methods from within Kotlin is a straightforward concept. The types of argument to provided are same in both Java and Kotlin and same is the case with the return type of the function. The only exception to this rule is the void return type. Those functions in Java which have a void return type, return a Unit type in Kotlin. So this value can be stored in Kotlin as Unit exists as a type.Java file declared as myjava.java  
Java
// Java codepublic class myjava {    public int add(int a, int b){        return a+b;    }}
Kotlin file declared as mykotlin.kt  
Java
// Kotlin filefun main(args: Array<String>) {    val obj = myjava()    val ans = obj.add(4, 5)    println("The sum of two numbers is "+ans)}
Output:  
The sum of two numbers is 9
Note – Some of the keywords of Kotlin are liable to be used as valid identifiers in Java. For example – any, sealed, object, etc. If this happens to be the case, then use identifiers in Kotlin, enclose them within a backtick character (`).For example, if a Java class XYZ happens to have a method named any, then the method can be called in Kotlin as:  
obj.`any`() // obj is the instance of the class XYZ
 
The static members of a class in Java become the members of a companion object in Kotlin. However, these companion objects cannot be used directly in expressions. To access, its members use the fully qualified name of the member as defined in Java.Java file declared as myjava.java  
Java
// Java Codepackage mypackage;    public class myjava {    public static void display() {        System.out.println("Call successful")    }}
Kotlin file declared as mykotlin.kt  
Java
// declare kotlin packagepackage myktpackage// import java class using java packageimport mypackage.myjava  fun main(args: Array<String>) {    // calling static member of java class    val str = myjava.display()    println(str)}
Output:  
Call successful
 
Kotlin supports an invariant form of Arrays, i.e. arrays of a particular type cannot be assigned to an array of type Any in Kotlin, which is different as compared to Java arrays that can be assigned to an array of type Object. Also, Kotlin doesn’t support the assignment of arrays of subclass types to an array of superclass type.Now, since Kotlin does not provide arrays for primitive types, it provides several specialized classes to represent an array of primitive types in Java. These classes have no relation to the Array class and get compiled into the primitive java arrays for maximum performance. This conversion to bytecode introduces no additional overhead, no matter the manner in which the arrays are used.Java file declared as myjava.java  
Java
// Java Codepublic class myjava {    int result = 0;    public int compute(int[] array)    {        for(int a: array){            result = result + a;        }        return result;    }}
Kotlin file declared as mykotlin.kt  
Java
// Kotlin codefun main(args: Array<String>) {    // Kotlin code    val obj = myjava()    val array = intArrayOf(1, 2, 3, 4, 5, 6)    var sum = obj.compute(array)    println("The sum of an array is "+sum)}
Output:  
The sum of an array is 21
 
Java supports the concept of variable-length arguments in functions i.e when the number of arguments to a function is not known in advance, but their type is known, we declare a varargs parameter. Kotlin doesn’t provide varargs parameters, however, to be fully operational with Java, it supports a special spread operator (*) to call the functions which have varargs parameters.Java file declared as myjava.java  
Java
// Java codepublic class myjava {    public void myfunc(String str,int... numbers) {        System.out.println("Passed string is " + str);        for (int n : numbers) {            System.out.print(" "+n);        }    }}
Kotlin file declared as mykotlin.kt  
Java
// Kotlin codefun main(args: Array<String>) {    val obj = myjava()    val array = intArrayOf(10, 20, 30)    obj.myfunc("Geeks", *array)}
Output:  
Passed string is Geeks
 10 20 30
 
Types in Kotlin are different from the types in Java. However, to maintain interoperability Kotlin provides a mapping from Java types to Kotlin types. This mapping takes place at compile time and no significant change in performance at runtime is observed.Java primitive types are mapped to the following primitive types:  
  Some of the built-in classes defined in the java.lang package is also mapped to Kotlin classes. 
  The boxed types of Java’s primitive data types are mapped to nullable types in Kotlin. 
 
nidhi_biet
abhishek0719kadiyan
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Change the Color of Status Bar in an Android App?
Suspend Function In Kotlin Coroutines
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin when expression