0
0
Kotlinprogramming~20 mins

Var for mutable references in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Mutable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using var?

Consider the following Kotlin code snippet. What will be printed?

Kotlin
fun main() {
    var number = 10
    number = 20
    println(number)
}
A20
B10
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint

Remember that var allows the variable to be changed.

Predict Output
intermediate
2:00remaining
What happens when you reassign a val variable?

What will happen when running this Kotlin code?

Kotlin
fun main() {
    val text = "Hello"
    text = "World"
    println(text)
}
AWorld
BRuntime exception
CHello
DCompilation error
Attempts:
2 left
💡 Hint

val means the variable cannot be reassigned.

Predict Output
advanced
2:00remaining
What is the output when modifying a mutable list declared with var?

Analyze this Kotlin code and determine the output.

Kotlin
fun main() {
    var list = mutableListOf(1, 2, 3)
    list.add(4)
    println(list)
}
A[1, 2, 3, 4]
BRuntime exception
C[1, 2, 3]
DCompilation error
Attempts:
2 left
💡 Hint

Mutable lists can be changed even if declared with var.

Predict Output
advanced
2:00remaining
What error occurs when trying to reassign a val mutable list?

What will happen when running this Kotlin code?

Kotlin
fun main() {
    val list = mutableListOf(1, 2, 3)
    list = mutableListOf(4, 5, 6)
    println(list)
}
A[4, 5, 6]
B[1, 2, 3]
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint

val means the reference cannot be changed, even if the object is mutable.

🧠 Conceptual
expert
2:00remaining
Why use var for mutable references in Kotlin?

Which statement best explains why var is used for mutable references in Kotlin?

A<p>Because <code>var</code> makes the object itself immutable.</p>
B<p>Because <code>var</code> allows changing the reference to point to a different object or value.</p>
C<p>Because <code>var</code> prevents any changes to the variable after initialization.</p>
D<p>Because <code>var</code> automatically synchronizes access in multithreaded code.</p>
Attempts:
2 left
💡 Hint

Think about what var allows you to do with a variable.