Challenge - 5 Problems
Val Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of val with mutable object
What is the output of this Kotlin code snippet?
Kotlin
data class Person(var name: String) fun main() { val person = Person("Alice") person.name = "Bob" println(person.name) }
Attempts:
2 left
💡 Hint
Remember val means the reference cannot change, but the object it points to can be modified if mutable.
✗ Incorrect
The val keyword makes the reference immutable, but the object itself can be changed if it has mutable properties. Here, person.name is changed from "Alice" to "Bob".
❓ Predict Output
intermediate2:00remaining
Reassigning val variable
What happens when you try to reassign a val variable in Kotlin?
Kotlin
fun main() { val number = 10 // number = 20 println(number) }
Attempts:
2 left
💡 Hint
val variables cannot be reassigned after initialization.
✗ Incorrect
Trying to assign a new value to a val variable causes a compilation error because val means the reference is immutable.
🔧 Debug
advanced2:00remaining
Why does this code fail to compile?
Identify the reason this Kotlin code does not compile.
Kotlin
fun main() { val list = listOf(1, 2, 3) list.add(4) println(list) }
Attempts:
2 left
💡 Hint
Check the type returned by listOf and what methods it supports.
✗ Incorrect
listOf returns an immutable list. The add() method is not available on immutable lists, so the code fails to compile.
🧠 Conceptual
advanced2:00remaining
Val and object mutability
Which statement best describes val in Kotlin regarding object mutability?
Attempts:
2 left
💡 Hint
Think about what val restricts: the reference or the object?
✗ Incorrect
val means the reference cannot be changed to point to another object, but the object itself can be mutable and changed.
❓ Predict Output
expert2:00remaining
Output with val and mutable collection
What is the output of this Kotlin program?
Kotlin
fun main() { val numbers = mutableListOf(1, 2, 3) val alias = numbers alias.add(4) println(numbers) }
Attempts:
2 left
💡 Hint
Both val variables point to the same mutable list object.
✗ Incorrect
Both numbers and alias refer to the same mutable list. Adding 4 via alias modifies the list, so printing numbers shows the updated list.