0
0
Kotlinprogramming~15 mins

Let function with safe calls in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Let Function with Safe Calls in Kotlin
📖 Scenario: Imagine you have a list of names that might contain some null values. You want to greet each person only if their name is not null. Using Kotlin's let function with safe calls helps you do this safely and cleanly.
🎯 Goal: Build a Kotlin program that uses the let function with safe calls to print greetings only for non-null names.
📋 What You'll Learn
Create a list called names with some String? values including null
Create a variable called greetingPrefix with the value "Hello"
Use a for loop to go through each name in names
Inside the loop, use a safe call with let to print a greeting only if the name is not null
💡 Why This Matters
🌍 Real World
Handling data that might be missing or null is common in apps. Using safe calls with let helps avoid errors and keeps code clean.
💼 Career
Many Kotlin jobs require safe handling of nullable data to prevent crashes and bugs, especially in Android development.
Progress0 / 4 steps
1
Create the list of names
Create a list called names with these exact values: "Alice", null, "Bob", null, "Charlie"
Kotlin
Need a hint?

Use listOf to create the list and include null where specified.

2
Add a greeting prefix
Create a variable called greetingPrefix and set it to the string "Hello"
Kotlin
Need a hint?

Use val to create an immutable variable for the greeting prefix.

3
Use let with safe calls to greet non-null names
Write a for loop using name to iterate over names. Inside the loop, use a safe call with name?.let to print "$greetingPrefix, $it!" only if name is not null
Kotlin
Need a hint?

Use name?.let { ... } to run code only when name is not null.

4
Print the greetings
Run the program to print greetings for all non-null names using the println statement inside the let block
Kotlin
Need a hint?

Make sure the println is inside the let block to print only for non-null names.