0
0
Kotlinprogramming~20 mins

Val for immutable references in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Val Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
AAlice
BRuntime exception
CCompilation error
DBob
Attempts:
2 left
💡 Hint
Remember val means the reference cannot change, but the object it points to can be modified if mutable.
Predict Output
intermediate
2: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)
}
ACompilation error if reassignment uncommented
BPrints 10
CPrints 20
DRuntime exception
Attempts:
2 left
💡 Hint
val variables cannot be reassigned after initialization.
🔧 Debug
advanced
2: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)
}
Aval variables cannot call functions
BlistOf creates a mutable list but val forbids modification
Clist is immutable, so add() is not available
Dprintln cannot print lists
Attempts:
2 left
💡 Hint
Check the type returned by listOf and what methods it supports.
🧠 Conceptual
advanced
2:00remaining
Val and object mutability
Which statement best describes val in Kotlin regarding object mutability?
Aval makes both the reference and the object immutable
Bval makes the reference immutable but the object can be mutable
Cval allows reassigning the reference but not modifying the object
Dval allows both reference reassignment and object mutation
Attempts:
2 left
💡 Hint
Think about what val restricts: the reference or the object?
Predict Output
expert
2: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)
}
A[1, 2, 3, 4]
BCompilation error due to val reassignment
CRuntime exception
D[1, 2, 3]
Attempts:
2 left
💡 Hint
Both val variables point to the same mutable list object.