val list = listOf(1, 2, 3) val newList = list.plus(4) println(list) println(newList)
The original list is immutable and does not change. The plus function returns a new list with the added element. So the first print shows the original list, and the second print shows the new list.
Immutable collections prevent accidental changes, which reduces bugs and makes programs easier to reason about. They also improve thread safety because no one can change the data unexpectedly.
val list = listOf(1, 2, 3) list.add(4)
Immutable lists do not have an add method. Trying to call add causes a compilation error because the method does not exist.
val mutableList = mutableListOf(1, 2, 3) mutableList.add(4) println(mutableList)
Mutable lists can be changed. The add method adds 4 to the list, so the print shows the updated list.
Immutable collections cannot be changed, so multiple threads can read them safely without locks or synchronization. This avoids common concurrency bugs.