0
0
Kotlinprogramming~15 mins

Safe casts with as? in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Safe casts with as? in Kotlin
📖 Scenario: Imagine you have a list of different types of objects, like numbers and words. You want to find out which ones are numbers and work with them safely without causing errors.
🎯 Goal: You will learn how to use the safe cast operator as? in Kotlin to convert objects to a specific type safely. This helps avoid crashes when the object is not of the expected type.
📋 What You'll Learn
Create a list called items with mixed types
Create a variable called countInts to count integers
Use a for loop with variables item to iterate over items
Use safe cast item as? Int inside the loop
Print the count of integers using print
💡 Why This Matters
🌍 Real World
Safe casts help when working with data from mixed sources, like user input or APIs, where types may vary.
💼 Career
Understanding safe casts is important for Kotlin developers to write robust and crash-free apps, especially in Android development.
Progress0 / 4 steps
1
Create a list with mixed types
Create a list called items with these exact values: 1, "hello", 3, "world", 5
Kotlin
Need a hint?

Use listOf() to create the list with the exact values.

2
Create a counter variable
Create a variable called countInts and set it to 0 to count how many integers are in the list
Kotlin
Need a hint?

Use var to create a variable that can change.

3
Use safe cast to count integers
Use a for loop with variable item to iterate over items. Inside the loop, use safe cast item as? Int to check if item is an integer. If it is, increase countInts by 1
Kotlin
Need a hint?

Use as? to safely cast and check for null before counting.

4
Print the count of integers
Write print(countInts) to display how many integers are in the list
Kotlin
Need a hint?

Use print() to show the final count.