Predict the output
Which line fails to compile?
fun main() {
val strings: List<String> = listOf("a")
val anys: List<Any> = strings
val mutableStrings: MutableList<String> = mutableListOf("a")
val mutableAnys: MutableList<Any> = mutableStrings
println(anys + mutableAnys)
}Hint 1 of 1
Which interface lets you add elements?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Line 5: MutableList is invariant
Correct. If it compiled, you could add an Int to the list of Strings.
Why not the others?
- B Line 3: List is invariant. List is declared List<out E>, so this is fine.
- C Both lines 3 and 5. Only the mutable one is invariant.
- D Neither. MutableList<String> isn't a MutableList<Any>.