Predict the output
What happens when you compile this?
fun main() {
val items = mutableListOf("a")
items.add("b")
items = mutableListOf("c")
println(items)
}Hint 1 of 1
What exactly is read-only about a val?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A It doesn't compile: a val can't be reassigned
Correct. add() is fine because the list is mutable, but the reference can't change.
Why not the others?
- B It prints [c]. The reassignment on line 4 isn't allowed.
- C It prints [a, b]. The code never runs; it fails to compile.
- D It fails on add(): a val list can't change. The list is a MutableList, so add() is allowed.