Skip to content
Related Articles

Related Articles

Improve Article

Java Interoperability – Calling Java from Kotlin

  • Last Updated : 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.
 

Getters and Setters in Java –

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 class
public 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 file
fun main(){
   val obj = myjava()
   obj.value = 5 // This will call the setter function
   println(obj.value) // This will call the getter function
}

Output: 
 



5

 

Methods –

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 code
public class myjava {
    public int add(int a, int b){
        return a+b;
    }
}

Kotlin file declared as mykotlin.kt 
 

Java




// Kotlin file
fun 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

 

Static members –

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 Code
package mypackage;
    public class myjava {
    public static void display() {
        System.out.println("Call successful")
    }
}

Kotlin file declared as mykotlin.kt 
 



Java




// declare kotlin package
package myktpackage
// import java class using java package
import mypackage.myjava 
 
fun main(args: Array<String>) {
    // calling static member of java class
    val str = myjava.display()
    println(str)
}

Output: 
 

Call successful

 

Java Arrays –

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 Code
public 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 code
fun 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 varargs –

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 code
public 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 code
fun 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

 

Java and Kotlin Mapped Types –

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: 
 

Java TypeKotlin Type
bytekotlin.Byte
shortkotlin.Short
intkotlin.Int
longkotlin.Long
charkotlin.Char
floatkotlin.Float
doublekotlin.Double
booleankotlin.Boolean

  
Some of the built-in classes defined in the java.lang package is also mapped to Kotlin classes.
 

Java TypeKotlin Type
java.lang.Objectkotlin.Any!
java.lang.Cloneablekotlin.Cloneable!
java.lang.Comparablekotlin.Comparable!
java.lang.Enumkotlin.Enum!
java.lang.annotationkotlin.Annotation!
java.lang.CharSequencekotlin.CharSequence
java.lang.Stringkotlin.String!
java.lang.Numberkotlin.Number!
java.lang.Throwablekotlin.Throwable!

  
The boxed types of Java’s primitive data types are mapped to nullable types in Kotlin.
 

Java TypeKotlin Type
java.lang.Bytekotlin.Byte?
java.lang.Shortkotlin.Short?
java.lang.Integerkotlin.Int?
java.lang.Longkotlin.Long?
java.lang.Characterkotlin.Char?
java.lang.Floatkotlin.Float?
java.lang.Doublekotlin.Double?
java.lang.Booleankotlin.Boolean?

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :