0
0
Kotlinprogramming~15 mins

Accessing elements safely in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing elements safely
📖 Scenario: You are working on a Kotlin program that manages a list of city names. Sometimes, the list might be empty or shorter than expected. You want to access elements safely without causing errors.
🎯 Goal: Build a Kotlin program that creates a list of cities, sets a safe index to access, retrieves the city safely using Kotlin's safe access methods, and prints the result.
📋 What You'll Learn
Create a list of cities with exact names
Create a variable for the index to access
Use safe access to get the city at the index or a default message
Print the accessed city or the default message
💡 Why This Matters
🌍 Real World
In real apps, lists might be empty or have fewer items than expected. Accessing elements safely prevents crashes and improves user experience.
💼 Career
Knowing how to safely access list elements is important for Kotlin developers working on Android apps or backend services to write robust and error-free code.
Progress0 / 4 steps
1
Create the list of cities
Create a list called cities with these exact city names in order: "Paris", "London", "New York", "Tokyo", "Sydney".
Kotlin
Need a hint?

Use listOf to create the list with the exact city names.

2
Set the index to access
Create an integer variable called index and set it to 3.
Kotlin
Need a hint?

Use val index = 3 to set the index.

3
Access the city safely
Create a variable called selectedCity that safely gets the city at index from cities. If the index is out of range, set selectedCity to the string "Unknown city". Use Kotlin's safe access methods.
Kotlin
Need a hint?

Use getOrNull(index) to get the city safely and the Elvis operator ?: to provide a default.

4
Print the selected city
Write a println statement to print the value of selectedCity.
Kotlin
Need a hint?

Use println(selectedCity) to display the city.