Sobes.tech
Junior — Middle

How to implement a list with an immutable data structure in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, to create an immutable list, the List interface is used, which provides only read methods without the ability to modify the contents.

To create such a list, you can use the listOf() function. This list cannot be changed — you cannot add, remove, or replace elements.

Example:

val immutableList: List<String> = listOf("apple", "banana", "cherry")

// immutableList.add("orange") // Compilation error

println(immutableList[1]) // Will output: banana

If you need a mutable copy, you can call toMutableList().

Thus, List in Kotlin is an immutable data structure that ensures safety from accidental modifications of the collection.