0
0
Kotlinprogramming~20 mins

Why scope functions reduce boilerplate in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Scope Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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)
AHello, !
BNo name
Cnull
DHello, Alice!
Attempts:
2 left
💡 Hint
Think about what happens when name is not null and how let works.
Predict Output
intermediate
1: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")
ABob is 0 years old
Bnull is 30 years old
CBob is 30 years old
D is 0 years old
Attempts:
2 left
💡 Hint
Remember that apply returns the object itself after running the block.
🔧 Debug
advanced
1: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)
AArithmeticException: / by zero
BNullPointerException
CSyntaxError
DNo error, prints 0
Attempts:
2 left
💡 Hint
Consider what happens when dividing by zero in Kotlin.
🧠 Conceptual
advanced
1:30remaining
Why does 'also' help reduce boilerplate?
Which statement best explains how the also scope function reduces boilerplate in Kotlin?
AIt replaces the need for constructors by initializing properties automatically.
BIt allows performing additional actions on an object without altering it, avoiding temporary variables.
CIt changes the object type to a different class to simplify code.
DIt forces the object to be immutable, reducing code complexity.
Attempts:
2 left
💡 Hint
Think about how also lets you do something extra with the object while keeping it unchanged.
Predict Output
expert
2: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}")
AHost: localhost, Port: 8080
BHost: localhost, Port: 0
CHost: , Port: 8080
DHost: , Port: 0
Attempts:
2 left
💡 Hint
Remember that apply and also both return the original object after running their blocks.