Recall & Review
beginner
What does the
let function do in Kotlin?The
let function executes a block of code on the object, passing the object as a parameter ('it') to the block. When used with safe calls (?.), it only executes if the object is not null.Click to reveal answer
beginner
How do safe calls work with
let in Kotlin?Safe calls (
?.) allow you to call let only if the object is not null, preventing null pointer exceptions.Click to reveal answer
beginner
Example: What will this code print?<br><pre>val name: String? = null
name?.let { println("Name is $it") }</pre>Nothing will be printed because
name is null, so let block is skipped.Click to reveal answer
intermediate
Why use
let with safe calls instead of a simple if check?let with safe calls makes code concise and readable by combining null check and action in one expression.Click to reveal answer
intermediate
What is the type of the parameter inside the
let block when used with safe calls?Inside the
let block, the parameter is the non-nullable version of the original object.Click to reveal answer
What happens when you use
?.let on a null object?✗ Incorrect
Using
?.let means the block runs only if the object is not null. If null, it skips safely.Inside a
let block called with safe call, the object is:✗ Incorrect
The object inside
let is smart cast to non-nullable because the block runs only if the object is not null.Which operator is used to safely call
let on a nullable object?✗ Incorrect
The safe call operator
?. calls let only if the object is not null.What is the main benefit of using
let with safe calls?✗ Incorrect
let with safe calls helps write concise, readable code by combining null check and action.What will this code print?<br>
val age: Int? = 25
age?.let { println("Age is $it") }✗ Incorrect
Since
age is not null, the let block runs and prints the age.Explain how the
let function works with safe calls in Kotlin and why it is useful.Think about how safe calls prevent errors and how let helps run code only when the object is not null.
You got /5 concepts.
Write a simple Kotlin example using a nullable variable with
?.let to print its value only if it is not null.Use a nullable variable and call <code>?.let</code> with a print inside the block.
You got /4 concepts.