Challenge - 5 Problems
Run Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that
run executes the block and returns the last expression.✗ Incorrect
The run function executes the block and returns the value of the last expression inside it. Here, x + y is the last expression, so result is 30.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The
run block returns the last expression's value, but println prints to console.✗ Incorrect
The run block prints Hello first, then returns this.length which is 5. So the console shows Hello and then 5.
🧠 Conceptual
advanced1:30remaining
Which statement about Kotlin's run function is true?
Choose the correct statement about the behavior of Kotlin's
run function.Attempts:
2 left
💡 Hint
Think about what
run returns after executing the block.✗ Incorrect
run is a standard library function that executes a block and returns the last expression's value. It does not modify the receiver permanently and is not limited to nullable types.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check how variable shadowing works inside the run block.
✗ Incorrect
Inside the run block, the local number variable shadows the outer one. The string "ten" has length 3, so result is 3 and prints 3.
🚀 Application
expert2: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)
Attempts:
2 left
💡 Hint
The run block returns the map after adding three entries.
✗ Incorrect
The run block creates a mutable map, adds three entries, and returns it. So the map size is 3.