0
0
Kotlinprogramming~30 mins

Null safety in collections in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Null Safety in Collections
📖 Scenario: You are building a simple contact list app. Some contacts may have missing phone numbers, so you need to handle null values safely in your list of contacts.
🎯 Goal: Create a list of contacts where some phone numbers can be null. Then, filter out the contacts without phone numbers using Kotlin's null safety features.
📋 What You'll Learn
Create a list of contacts with names and nullable phone numbers
Create a variable to hold the filtered list of contacts with non-null phone numbers
Use Kotlin's safe call operator and filtering to keep only contacts with phone numbers
Print the filtered list of contacts
💡 Why This Matters
🌍 Real World
Handling contact lists or any data where some information might be missing is common in apps like phonebooks, messaging, or customer management.
💼 Career
Understanding null safety in collections helps prevent crashes and bugs in real-world Kotlin applications, a key skill for Android developers and backend Kotlin programmers.
Progress0 / 4 steps
1
Create a list of contacts with nullable phone numbers
Create a list called contacts with these exact entries: "Alice" to "123-4567", "Bob" to null, "Charlie" to "987-6543", and "Diana" to null. 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 numbers can be null.

2
Create a variable to hold filtered contacts
Create a variable called contactsWithPhone and set it to an empty list of pairs with String and nullable String types.
Kotlin
Need a hint?

Use var contactsWithPhone: List> = listOf() to create an empty list with the right type.

3
Filter contacts to keep only those with phone numbers
Set contactsWithPhone to a filtered list from contacts that keeps only pairs where the phone number (second value) is not null. Use filter and check it.second != null.
Kotlin
Need a hint?

Use contacts.filter { it.second != null } to keep only contacts with phone numbers.

4
Print the filtered contacts
Print contactsWithPhone using println to show the contacts that have phone numbers.
Kotlin
Need a hint?

Use println(contactsWithPhone) to display the filtered list.