0
0
Kotlinprogramming~15 mins

Safe call operator (?.) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Safe Call Operator (?.) in Kotlin
📖 Scenario: Imagine you have a list of people, and each person may or may not have a phone number. You want to safely print the length of each phone number without causing errors if the phone number is missing.
🎯 Goal: Build a Kotlin program that uses the safe call operator ?. to safely access the length of phone numbers in a list of people.
📋 What You'll Learn
Create a list of people with nullable phone numbers
Create a variable to hold the count of people
Use the safe call operator ?. to get the length of each phone number safely
Print the length of each phone number or null if missing
💡 Why This Matters
🌍 Real World
Handling data where some information might be missing is common in apps, like user profiles with optional phone numbers.
💼 Career
Knowing how to safely access nullable data prevents crashes and bugs in real-world Kotlin applications.
Progress0 / 4 steps
1
Create a list of people with nullable phone numbers
Create a list called people with these exact entries: "Alice" to "12345", "Bob" to null, "Charlie" to "987654321". Use a list of pairs where the second value can be null.
Kotlin
Need a hint?

Use listOf with pairs like "Name" to phoneNumber. Phone number can be null.

2
Create a variable to hold the count of people
Create a variable called count and set it to the size of the people list using people.size.
Kotlin
Need a hint?

Use val count = people.size to get the number of people.

3
Use the safe call operator to get phone number lengths
Create a list called lengths that contains the length of each phone number using people.map. Use the safe call operator ?. on the phone number to get its length safely.
Kotlin
Need a hint?

Use people.map { it.second?.length } to get lengths safely.

4
Print the lengths of phone numbers
Print the lengths list using println(lengths).
Kotlin
Need a hint?

Use println(lengths) to show the list of lengths.