Read-only collections in Kotlin, leads to better coding.

In Kotlin, if you create a List or Map, it is Read-Only (similar to Immutable, but slightly different). What this means is, you have no add or put or remove function to add to or remove from the collection once it is constructed.

Note: if you still like to have a mutable collection, you would need to declare a MutableList or MutableMap. My recommendation is only to do that if you really need a temporary list that is mutable.

How to create Read-Only Collections

In Java, to create a List, it would normally as below

List<String> countries = new ArrayList();
countries.add("Australia");
countries.add("Korea");
countries.add("Malaysia");

But we can’t do the same in Kotlin anymore, as you can’t add to the List after it is created.

So to do as the above, you would use the listOf function provided by CollectionKt class of Kotlin.

val countries = listOf("Australia", "Korea", "Malaysia")

Similarly for Map, you could use mapOf function as below.

val mapCountryCapital = mapOf(
Pair("Australia", "Canberra"),
Pair("Malaysia", "Putrajaya"))

Filter a collection

--

--