0
0
Kotlinprogramming~20 mins

Let function with safe calls in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Let Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of let with safe call on nullable String
What is the output of this Kotlin code snippet?
Kotlin
val name: String? = "Anna"
val result = name?.let { it.uppercase() } ?: "No name"
println(result)
AANNA
BNo name
Canna
Dnull
Attempts:
2 left
💡 Hint
Remember that let runs only if the value is not null and uppercase converts to capital letters.
Predict Output
intermediate
2:00remaining
Result of let with null value and safe call
What will be printed by this Kotlin code?
Kotlin
val number: Int? = null
val output = number?.let { it * 2 } ?: -1
println(output)
AException
B-1
Cnull
D0
Attempts:
2 left
💡 Hint
If the variable is null, let block does not run and the Elvis operator ?: provides the default.
🔧 Debug
advanced
2:00remaining
Identify the error in let with safe call
This Kotlin code is intended to print the length of a nullable string if it is not null. What error will it produce?
Kotlin
val text: String? = null
val length = text.let { it.length }
println(length)
APrints 0
BNullPointerException
CCompilation error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver
DPrints null
Attempts:
2 left
💡 Hint
Check how let is called on a nullable variable without safe call operator.
Predict Output
advanced
2:00remaining
Output of nested let with safe calls
What is the output of this Kotlin code?
Kotlin
val a: String? = "Hi"
val b: String? = null
val result = a?.let { x -> b?.let { y -> x + y } } ?: "Empty"
println(result)
AEmpty
BHi
CHinull
Dnull
Attempts:
2 left
💡 Hint
The inner let runs only if b is not null. If b is null, the whole expression after ?: is used.
Predict Output
expert
2:00remaining
Value of variable after let with safe call and side effect
Consider this Kotlin code. What is the final value of the variable 'counter' after execution?
Kotlin
var counter = 0
var text: String? = "abc"
text?.let {
    counter += it.length
}
text = null
text?.let {
    counter += it.length
}
println(counter)
ACompilation error
B0
C6
D3
Attempts:
2 left
💡 Hint
The let block runs only when the variable is not null. The second let does not run because text is null.