I'm sorry, I tried to change my example into something more concise, without testing. The original code snippet:
import kotlin.test.*
fun main() {
val a = listOf(
Person("John", 33),
Person("Doe", 50)
)
val b = a.filter { it.age < 40 }
a[0].age = 10
assertEquals(
b[0].age,
10,
"Modifying a results in modifying b, because the elements are references"
)
}
data class Person(var name: String, var age: Int)
This only seems to happen to Object
's in java, as they are handled as references in the JVM. Because of the var
keyword in the Person
class those fields can be modified without the need of "mutating" the array.