Pim
01/31/2025, 10:46 AMclass Persons {
private val _persons = mutableListOf("Person1", "Person2")
val entries: List<String>
get() = _persons.toList()
fun addPerson(person: String) {
_persons.add(person)
}
}
The idea is that the Persons
class keeps an internal mutable list. External users of the Persons
class can read an immutable version of the list.
Now I tried playing around with casting the received list from entries
back to a MutableList<String>
to see if I can then start adding things back into the list.
I ran the following code:
fun main() {
val persons = Persons()
println(persons.entries.joinToString())
persons.addPerson("Person3")
println(persons.entries.joinToString())
(persons.entries as MutableList<String>).add("Person4")
println(persons.entries.joinToString())
(persons.entries as MutableList<String>).also { it.add("Person4") }.joinToString()
println(persons.entries.joinToString())
}
The output surprises me. I get not warnings or compilation errors, but the "Person4"
is never actually added?
Output:
Person1, Person2
Person1, Person2, Person3
Person1, Person2, Person3
Person1, Person2, Person3
Could someone help me explain what happens here, and especially what happens on: (persons.entries as MutableList<String>).also { it.add("Person4") }.joinToString()
.
Does casting with as
give you a new object?Riccardo Lippolis
01/31/2025, 10:50 AM_persons.toList()
returns a new instance of a List, which contains all the elements present in _persons
at the time of creation.
So when you call
(persons.entries as MutableList<String>).add("Person4")
you are adding the Person4
string to a new List instance, that is instantly lost because you don't have any more reference to it. The same applies to
(persons.entries as MutableList<String>).also { it.add("Person4") }.joinToString()
which creates a String, but does not print it.
If you do this:
println((persons.entries as MutableList<String>).also { it.add("Person4") }.joinToString())
you will see Person4
in the output. But still, it is not present the next time you call persons.entries
, because that is again a new List instancePim
01/31/2025, 10:58 AM