Challenge - 5 Problems
Mutable vs Immutable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of modifying a mutable list via interface
What is the output of this Kotlin code snippet?
Kotlin
val list: MutableList<Int> = mutableListOf(1, 2, 3) val readOnlyList: List<Int> = list list.add(4) println(readOnlyList.size)
Attempts:
2 left
💡 Hint
Think about whether the readOnlyList reflects changes to the original mutable list.
✗ Incorrect
The readOnlyList is a reference to the same mutable list. Adding an element to the mutable list changes its size, so readOnlyList.size is 4.
🧠 Conceptual
intermediate2:00remaining
Difference between MutableList and List interfaces
Which statement correctly describes the difference between Kotlin's MutableList and List interfaces?
Attempts:
2 left
💡 Hint
Consider which interface provides methods like add, remove, or clear.
✗ Incorrect
MutableList extends List and adds methods to modify the collection. List only provides read-only access.
❓ Predict Output
advanced2:00remaining
Output when casting mutable to immutable and modifying
What is the output of this Kotlin code?
Kotlin
val mutable: MutableList<String> = mutableListOf("a", "b") val immutable: List<String> = mutable (mutable as MutableList<String>).add("c") println(immutable.size)
Attempts:
2 left
💡 Hint
Remember that immutable is just a reference to the same mutable list.
✗ Incorrect
The immutable variable points to the same mutable list. Adding "c" increases the size to 3, so printing immutable.size outputs 3.
❓ Predict Output
advanced2:00remaining
Error when trying to modify an immutable list
What error does this Kotlin code produce?
Kotlin
val list: List<Int> = listOf(1, 2, 3) list.add(4)
Attempts:
2 left
💡 Hint
Check if List interface has an add method.
✗ Incorrect
The List interface in Kotlin does not have an add method, so calling list.add(4) causes a compilation error: Unresolved reference: add.
🧠 Conceptual
expert3:00remaining
Why prefer immutable interfaces in API design?
Which is the best reason to expose immutable interfaces (like List) instead of mutable ones (like MutableList) in Kotlin API design?
Attempts:
2 left
💡 Hint
Think about controlling how data is changed by users of your API.
✗ Incorrect
Exposing immutable interfaces prevents clients from changing internal data, which helps maintain data integrity and reduces bugs.