Hey all, I'm playing around with lists and mutabl...
# getting-started
p
Hey all, I'm playing around with lists and mutable lists. I have the following class that I use to test on:
Copy code
class 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:
Copy 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:
Copy code
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?
r
_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
Copy code
(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
Copy code
(persons.entries as MutableList<String>).also { it.add("Person4") }.joinToString()
which creates a String, but does not print it. If you do this:
Copy code
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 instance
gratitude thank you 1
p
Makes sense now thanks a lot!