Calling the Java collection in Kotlin

Create a method in Java that returns an arrayList of integers:

public static ArrayList<Integer> getIntList(){

ArrayList<Integer> integers = new ArrayList<>();
integers.add(1);integers.add(2);integers.add(3);

return integers;
}

getIntList returns an array that contains three elements. Call this function in Kotlin to access the list and add more elements in it:

var list = CallJava.getIntList()
//var list: ArrayList<Int> = CallJava.getIntList()

list.add(4)
for (element in list) {
println("Element $element")
}

CallJava.getIntList() returns ArrayList, which can be assigned to a list type of variables. We explicitly declare the type of the list by using the ArrayList<Int> name:

var list: ArrayList<Int> = CallJava.getIntList()

Alternatively, we can directly assign a list to the variable and Kotlin will figure out the list type by itself:

var list = CallJava.getIntList()

We can treat this as a normal immutable list and we can add or remove elements.

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

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