0
0
Kotlinprogramming~20 mins

Why immutable collections are default in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Immutable Collections Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of modifying a Kotlin immutable list
What is the output of this Kotlin code snippet?
Kotlin
val list = listOf(1, 2, 3)
val newList = list.plus(4)
println(list)
println(newList)
ACompilation error
B
[1, 2, 3, 4]
[1, 2, 3, 4]
C
[1, 2, 3]
[1, 2, 3]
D
[1, 2, 3]
[1, 2, 3, 4]
Attempts:
2 left
💡 Hint
Remember that listOf creates an immutable list and plus returns a new list.
🧠 Conceptual
intermediate
1:30remaining
Reason for default immutability in Kotlin collections
Why does Kotlin make collections immutable by default?
ATo prevent accidental changes and improve thread safety
BBecause mutable collections are deprecated
CTo make collections slower but safer
DBecause Kotlin does not support mutable collections
Attempts:
2 left
💡 Hint
Think about safety and bugs in programs.
🔧 Debug
advanced
2:00remaining
Identify the error when modifying an immutable list
What error does this Kotlin code produce?
Kotlin
val list = listOf(1, 2, 3)
list.add(4)
AUnsupportedOperationException at runtime
BUnresolved reference: add
CCompilation error: val cannot be reassigned
DNo error, list is modified
Attempts:
2 left
💡 Hint
Check if immutable lists have an add method.
Predict Output
advanced
1:30remaining
Output of modifying a mutable list
What is the output of this Kotlin code?
Kotlin
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
println(mutableList)
ACompilation error
B[1, 2, 3]
C[1, 2, 3, 4]
DRuntime exception
Attempts:
2 left
💡 Hint
Mutable lists allow adding elements.
🧠 Conceptual
expert
2:30remaining
Why prefer immutable collections in concurrent programming?
Why are immutable collections preferred in concurrent programming?
ABecause they avoid synchronization issues by not allowing changes
BBecause they allow multiple threads to write safely at the same time
CBecause they are faster to modify than mutable collections
DBecause they automatically lock data for each thread
Attempts:
2 left
💡 Hint
Think about what happens if many threads try to change data at once.