Let's run an experiment:
class Foo {
@Test
fun foo() {
val items = mutableListOf("A")
run(items)
Thread.sleep(1000)
items.add("B")
println("Foo")
Thread.sleep(2000)
}
fun run(items: List<String>) {
thread(start = true) {
println("Run ${items.count()}")
Thread.sleep(2000)
println("Run ${items.count()}")
}
}
}
This test case will create a mutable list of 1 item, it will then pass a reference to this list into a method whose type is for an immutable list.
This method called run will diplay the length of the list.
Outside of the run method a new item will be appended to the list.
sleeps have been added ensure that the addition to the list happen after run's first statement but before the second print statement.
Let's examine the output:
Run 1
Foo
Run 2
As we can see, the list contents did indeed change, even though run took in an immutable list.
This is because MutableList and List are merely interfaces and all MutableList implementations also implement List.
When Kotlin refers to mutable and immutable it simply references whether the methods to modify the collection are present, not whether the contents can be changed.
So if you take in a list to a method using List as the parameter type then yes, the contents can vary if they are altered by another thread, if that is a concern then make a copy of the list as the first thing your method does.