0
0
Kotlinprogramming~20 mins

Run function behavior and use cases in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Run Function Mastery
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 run?
Consider the following Kotlin code snippet using the run function. What will be printed when this code runs?
Kotlin
val result = run {
    val x = 10
    val y = 20
    x + y
}
println(result)
ACompilation error
B20
C30
D10
Attempts:
2 left
💡 Hint
Remember that run executes the block and returns the last expression.
Predict Output
intermediate
2:00remaining
What does this run block return?
Look at this Kotlin code using run. What is the value of output after running this?
Kotlin
val output = "Hello".run {
    println(this)
    this.length
}
println(output)
ACompilation error
BHello\n5
C5
DHello\nHello
Attempts:
2 left
💡 Hint
The run block returns the last expression's value, but println prints to console.
🧠 Conceptual
advanced
1:30remaining
Which statement about Kotlin's run function is true?
Choose the correct statement about the behavior of Kotlin's run function.
A<code>run</code> is a keyword and cannot be used as a function.
B<code>run</code> can only be used with nullable types.
C<code>run</code> modifies the receiver object permanently.
D<code>run</code> executes a block and returns the last expression's value.
Attempts:
2 left
💡 Hint
Think about what run returns after executing the block.
🔧 Debug
advanced
2:00remaining
What error does this Kotlin code cause?
Examine this Kotlin code using run. What error will it produce when compiled or run?
Kotlin
val number = 5
val result = number.run {
    val number = "ten"
    number.length
}
println(result)
APrints 3
BPrints 5
CCompilation error due to variable shadowing
DRuntime NullPointerException
Attempts:
2 left
💡 Hint
Check how variable shadowing works inside the run block.
🚀 Application
expert
2:30remaining
How many items are in the map created by this run block?
What is the number of entries in the map returned by this Kotlin run block?
Kotlin
val map = run {
    val tempMap = mutableMapOf<Int, String>()
    tempMap[1] = "one"
    tempMap[2] = "two"
    tempMap[3] = "three"
    tempMap
}
println(map.size)
A3
B0
C1
DCompilation error
Attempts:
2 left
💡 Hint
The run block returns the map after adding three entries.