0
0
Kotlinprogramming~20 mins

Testing scope functions and lambdas in Kotlin - Practice Problems & Coding Challenges

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
2:00remaining
Output of nested scope functions with lambdas
What is the output of this Kotlin code snippet?
Kotlin
val result = "Hello".run {
    val upper = this.uppercase()
    also { println("Inside also: $it") }
    lowercase()
}
println(result)
A
Inside also: hello
hello
B
Inside also: HELLO
hello
C
Inside also: Hello
hello
D
Inside also: Hello
HELLO
Attempts:
2 left
💡 Hint
Remember what 'run' and 'also' return and what 'this' and 'it' refer to inside lambdas.
Predict Output
intermediate
2:00remaining
Return value of 'apply' with lambda
What does this Kotlin code print?
Kotlin
val list = mutableListOf(1, 2, 3).apply {
    add(4)
    remove(2)
}
println(list)
A[1, 3]
B[1, 2, 3, 4]
C[4]
D[1, 3, 4]
Attempts:
2 left
💡 Hint
Recall that 'apply' returns the object it was called on after running the lambda.
Predict Output
advanced
2:00remaining
Effect of 'let' on nullable types
What is the output of this Kotlin code?
Kotlin
val name: String? = null
val length = name?.let {
    println("Name is not null: $it")
    it.length
} ?: -1
println(length)
A-1
B
Name is not null: null
0
C
Name is not null: null
-1
DNullPointerException
Attempts:
2 left
💡 Hint
Check how safe call operator and 'let' work with null values.
Predict Output
advanced
2:00remaining
Output of 'also' modifying external variable
What will be printed by this Kotlin code?
Kotlin
var count = 0
val result = listOf(1, 2, 3).also {
    count = it.sum()
}
println("count = $count, result = $result")
Acount = 6, result = [1, 2, 3]
Bcount = 0, result = 6
Ccount = 6, result = 6
Dcount = 0, result = [1, 2, 3]
Attempts:
2 left
💡 Hint
'also' returns the original object but allows side effects inside the lambda.
Predict Output
expert
3:00remaining
Complex chaining of scope functions and lambdas
What is the output of this Kotlin code?
Kotlin
val output = mutableListOf<String>().run {
    add("Start")
    apply {
        add("Middle")
        also {
            add("Almost End")
        }
    }
    add("End")
    this
}
println(output)
A[Start, Almost End, End]
B[Start, Middle, Almost End, End]
C[Start, Middle, End]
D[Start, Middle, Almost End]
Attempts:
2 left
💡 Hint
Trace each scope function carefully and remember what each returns.