Functions with immutable collections

Let's see how to get an immutable list from the Kotlin function to Java. Create an immutable list in the getImmutableList function and return the list:

fun getImmutableList() : List<Int> {
val list = listOf(1,2,3,4,5)
return list
}

Get a Kotlin list by calling the getImmutableList function and displaying list elements. See the following example:

public static void main(String args[]) {
System.out.println("Kotlin immutable list");

List<Integer> listFromKotlin = CallKotlinKt.getImmutableList();

for (int i = 0; i < listFromKotlin.size(); i++) {
System.out.println("Element " + listFromKotlin.get(i));
}
}

Since we know that the immutable list cannot be updated, we can read the list but cannot add or update elements. Once the immutable list is called in Java, it is the programmer's responsibility to verify the type of list before updating it because the Java compiler could not catch the error at compile time. If we try to add an element in the immutable list of Kotlin, we will get the following result:

List<Integer> listFromKotlin = KotlinToJavaKt.getImmutableList();
listFromKotlin.add(6);

This shows that Java will throw the java.lang.UnsupportedOperationException exception at runtime and the application will crash.

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

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