0
0
Kotlinprogramming~20 mins

Mutable vs immutable interfaces in Kotlin - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Mutable vs Immutable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A4
B3
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Think about whether the readOnlyList reflects changes to the original mutable list.
🧠 Conceptual
intermediate
2:00remaining
Difference between MutableList and List interfaces
Which statement correctly describes the difference between Kotlin's MutableList and List interfaces?
AMutableList allows modification of elements, List does not allow any modification.
BList allows modification of elements, MutableList does not.
CBoth MutableList and List allow modification but MutableList has extra methods.
DNeither MutableList nor List allow modification of elements.
Attempts:
2 left
💡 Hint
Consider which interface provides methods like add, remove, or clear.
Predict Output
advanced
2: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)
A2
BCompilation error
CClassCastException
D3
Attempts:
2 left
💡 Hint
Remember that immutable is just a reference to the same mutable list.
Predict Output
advanced
2: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)
AUnsupportedOperationException at runtime
BUnresolved reference: add
CCompilation error: val cannot be reassigned
DNo error, list becomes [1, 2, 3, 4]
Attempts:
2 left
💡 Hint
Check if List interface has an add method.
🧠 Conceptual
expert
3: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?
ATo improve performance by disabling modifications
BBecause immutable interfaces have more methods
CTo prevent clients from modifying internal data accidentally
DTo allow clients to add elements safely
Attempts:
2 left
💡 Hint
Think about controlling how data is changed by users of your API.