0
0
Kotlinprogramming~20 mins

Chaining scope functions in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Scope Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of chained scope functions with let and also
What is the output of this Kotlin code snippet?
Kotlin
val result = "hello".let {
    println(it.uppercase())
    it.length
}.also {
    println(it * 2)
}
println(result)
A
hello
10
5
B
HELLO
5
10
C
HELLO
10
5
D
HELLO
5
5
Attempts:
2 left
💡 Hint
Remember that let returns the last expression inside its block, and also returns the receiver.
Predict Output
intermediate
2:00remaining
Result of chaining apply and run
What will be printed by this Kotlin code?
Kotlin
val builder = StringBuilder().apply {
    append("Hi")
}.run {
    append(" there")
    toString()
}
println(builder)
Athere
BHi thereHi
CHi
DHi there
Attempts:
2 left
💡 Hint
apply returns the receiver, run returns the last expression.
🔧 Debug
advanced
2:00remaining
Identify the error in chained let and with
What error does this Kotlin code produce?
Kotlin
val text = "abc".let {
    it.uppercase()
}.with {
    println(this)
    length
}
println(text)
AUnresolved reference: length
BType mismatch: inferred type is Unit but Int was expected
CNo error, prints ABC and 3
DNullPointerException
Attempts:
2 left
💡 Hint
The let block returns the result of the last expression: it.uppercase(), which is a String.
Predict Output
advanced
2:00remaining
Output of nested run and also with mutable list
What is the output of this Kotlin code?
Kotlin
val list = mutableListOf(1, 2, 3).run {
    add(4)
    also {
        it.removeAt(0)
    }
    size
}
println(list)
A3
B4
C5
DCompilation error
Attempts:
2 left
💡 Hint
Remember what run returns and what also returns.
🧠 Conceptual
expert
3:00remaining
Understanding return values in chained scope functions
Given the Kotlin code below, what is the final value of result?
Kotlin
val result = "Kotlin".also {
    println(it.lowercase())
}.let {
    it.length
}.apply {
    println(this)
}
AUnit
B6
CCompilation error
DKotlin
Attempts:
2 left
💡 Hint
Check what apply returns and what let returns.