Challenge - 5 Problems
Kotlin Let Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput 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)
Attempts:
2 left
💡 Hint
Remember that let runs only if the value is not null and uppercase converts to capital letters.
✗ Incorrect
The safe call ?. lets the let block run only if name is not null. Since name is "Anna", let converts it to uppercase, so output is "ANNA".
❓ Predict Output
intermediateResult 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)
Attempts:
2 left
💡 Hint
If the variable is null, let block does not run and the Elvis operator ?: provides the default.
✗ Incorrect
Since number is null, the safe call ?. skips let and the Elvis operator returns -1, so output is -1.
🔧 Debug
advancedIdentify 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)
Attempts:
2 left
💡 Hint
Check how let is called on a nullable variable without safe call operator.
✗ Incorrect
Calling let directly on a nullable variable without safe call causes a compilation error because the receiver might be null.
❓ Predict Output
advancedOutput 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)
Attempts:
2 left
💡 Hint
The inner let runs only if b is not null. If b is null, the whole expression after ?: is used.
✗ Incorrect
Since b is null, b?.let does not run and the outer let returns null, so Elvis operator returns "Empty".
❓ Predict Output
expertValue 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)
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.
✗ Incorrect
The first let runs and adds 3 to counter. The second let does not run because text is null. So counter is 3.
