Challenge - 5 Problems
Scope Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of using 'let' to avoid null checks
What is the output of this Kotlin code using the
let scope function?Kotlin
val name: String? = "Alice" val result = name?.let { "Hello, $it!" } ?: "No name" println(result)
Attempts:
2 left
💡 Hint
Think about what happens when
name is not null and how let works.✗ Incorrect
The let function executes the block only if name is not null. Here, name is "Alice", so the block returns "Hello, Alice!". The Elvis operator ?: is not used.
❓ Predict Output
intermediate1:30remaining
Using 'apply' to initialize an object
What does this Kotlin code print?
Kotlin
class Person { var name: String = "" var age: Int = 0 } val person = Person().apply { name = "Bob" age = 30 } println("${person.name} is ${person.age} years old")
Attempts:
2 left
💡 Hint
Remember that
apply returns the object itself after running the block.✗ Incorrect
The apply function runs the block on the object and returns the object itself. Here, it sets name and age before returning the Person instance.
🔧 Debug
advanced1:30remaining
Identify the error in this 'run' usage
What error does this Kotlin code produce?
Kotlin
val result = run { val x = 10 val y = 0 x / y } println(result)
Attempts:
2 left
💡 Hint
Consider what happens when dividing by zero in Kotlin.
✗ Incorrect
The code divides 10 by 0 inside run. This causes an ArithmeticException for division by zero at runtime.
🧠 Conceptual
advanced1:30remaining
Why does 'also' help reduce boilerplate?
Which statement best explains how the
also scope function reduces boilerplate in Kotlin?Attempts:
2 left
💡 Hint
Think about how
also lets you do something extra with the object while keeping it unchanged.✗ Incorrect
also lets you run code using the object as it and returns the original object unchanged. This avoids creating extra variables or repeating the object reference.
❓ Predict Output
expert2:00remaining
Output of nested scope functions
What is the output of this Kotlin code using nested scope functions?
Kotlin
data class Config(var host: String = "", var port: Int = 0) val config = Config().apply { host = "localhost" }.also { it.port = 8080 } println("Host: ${config.host}, Port: ${config.port}")
Attempts:
2 left
💡 Hint
Remember that
apply and also both return the original object after running their blocks.✗ Incorrect
The apply block sets host to "localhost" and returns the object. Then also sets port to 8080 on the same object. The final print shows both updated values.