Java Interoperability – Calling Java from Kotlin

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



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java class
public class myjava {
  private int value;
  public int getValue(){
       return value;
  }
  public void setValue(int value){
       this.value = value;
  }
}

chevron_right


Kotlin file declared as mykotlin.kt

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code
public class myjava {
    public int add(int a, int b){
        return a+b;
    }
}

chevron_right


Koltin file declared as mykotlin.kt

filter_none

edit
close

play_arrow

link
brightness_4
code

// Kotlin file
fun main(args: Array<String>) {
    val obj = myjava()
    val ans = obj.add(4, 5)
    println("The sum of two numbers is "+ans)
}

chevron_right


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


filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code
package mypackage;
    public class myjava {
    public static void display() {
        System.out.println("Call successfull")
    }
}

chevron_right


Kotlin file declared as mykotlin.kt

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

Call successfull

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code
public class myjava {
    int result = 0;
    public int compute(int[] array)
    {
        for(int a: array){
            result = result + a;
        }
        return result;
    }
}

chevron_right


Kotlin file declared as mykotlin.kt

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
        }
    }
}

chevron_right


Kotlin file declared as mykotlin.kt


filter_none

edit
close

play_arrow

link
brightness_4
code

// Kotlin code
fun main(args: Array<String>) {
    val obj = myjava()
    val array = intArrayOf(10, 20, 30)
    obj.myfunc("Geeks", *array)
}

chevron_right


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 Type Kotlin Type
byte kotlin.Byte
short kotlin.Short
int kotlin.Int
long kotlin.Long
char kotlin.Char
float kotlin.Float
double kotlin.Double
boolean kotlin.Boolean

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

Java Type Kotlin Type
java.lang.Object kotlin.Any!
java.lang.Cloneable kotlin.Cloneable!
java.lang.Comparable kotlin.Comparable!
java.lang.Enum kotlin.Enum!
java.lang.annotation kotlin.Annotation!
java.lang.CharSequence kotlin.CharSequence
java.lang.String kotlin.String!
java.lang.Number kotlin.Number!
java.lang.Throwable kotlin.Throwable!

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

Java Type Kotlin Type
java.lang.Byte kotlin.Byte?
java.lang.Short kotlin.Short?
java.lang.Integer kotlin.Int?
java.lang.Long kotlin.Long?
java.lang.Character kotlin.Char?
java.lang.Float kotlin.Float?
java.lang.Double kotlin.Double?
java.lang.Boolean kotlin.Boolean?


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.