Back to questions
JuniorTheoryCommon
What does the program print?
fun main() {
val items = mutableListOf(1, 2)
val view: List<Int> = items
items.add(3)
println(view)
}[1, 2, 3]
- Expecting
[1, 2]: giving a list aListname copies nothing.viewanditemsname one list, soviewsees the3added throughitems. - Expecting
valto forbidadd:valonly stopsitemsfrom naming another list; the list itself can still grow withadd.
- How would you change the program so that
println(view)prints[1, 2]? - Why does
view.add(4)not compile even thoughitems.add(3)does?