📖 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
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
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
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
Hint
Use print() to show the final count.
Practice
(1/5)
1.
What does the safe cast operator as? do in Kotlin?
easy
A. It converts a value to a string representation.
B. It forces a cast and throws an exception if it fails.
C. It tries to cast a value to a type and returns null if it fails.
D. It checks if a value is null without casting.
Solution
Step 1: Understand the safe cast operator
The as? operator attempts to cast a value to a specified type safely.
Step 2: Behavior on failure
If the cast is not possible, instead of throwing an error, it returns null.
Final Answer:
It tries to cast a value to a type and returns null if it fails. -> Option C
Quick Check:
Safe cast = returns null on failure [OK]
Hint: Safe cast returns null if cast fails, no crash [OK]
Common Mistakes:
Confusing safe cast with forced cast
Thinking it throws an exception on failure
Assuming it converts to string automatically
2.
Which of the following is the correct syntax for a safe cast in Kotlin?
val x = obj ___ String
easy
A. as?
B. to
C. is
D. as
Solution
Step 1: Identify safe cast syntax
In Kotlin, the safe cast operator is as? which tries to cast safely.
Step 2: Match syntax to code
The code val x = obj as? String attempts to cast obj to String safely.
Final Answer:
as? -> Option A
Quick Check:
Safe cast syntax = as? [OK]
Hint: Safe cast uses as? with question mark [OK]
Common Mistakes:
Using as without question mark causes exception
Confusing is (type check) with as? (cast)
Using to which is for conversions, not casting
3.
What will be the output of this Kotlin code?
val obj: Any = 123
val str: String? = obj as? String
println(str)
medium
A. null
B. ClassCastException
C. 123
D. "123"
Solution
Step 1: Analyze the cast attempt
Variable obj holds an integer 123, but we try to cast it to String using safe cast as?.
Step 2: Safe cast behavior
Since obj is not a String, the safe cast returns null instead of throwing an error.
Final Answer:
null -> Option A
Quick Check:
Safe cast fails = null output [OK]
Hint: Safe cast returns null if types mismatch [OK]
Common Mistakes:
Expecting ClassCastException instead of null
Thinking it converts integer to string automatically
Confusing safe cast with forced cast
4.
Identify the error in this Kotlin code snippet and fix it:
val obj: Any = "Hello"
val num: Int = obj as? Int
println(num)
medium
A. Replace as? with as
B. Change val num: Int to val num: Int?
C. Cast obj to String instead of Int
D. No error, code runs fine
Solution
Step 1: Analyze variable types and cast
The safe cast obj as? Int returns null if cast fails, so the result is nullable Int?.
Step 2: Fix type mismatch
Declaring num as non-nullable Int causes a type mismatch error. Changing it to Int? fixes this.
Final Answer:
Change val num: Int to val num: Int? -> Option B
Quick Check:
Safe cast returns nullable type [OK]
Hint: Safe cast result must be nullable type [OK]
Common Mistakes:
Using non-nullable type for safe cast result
Replacing safe cast with forced cast causing exceptions
Ignoring type mismatch errors
5.
You have a list of Any objects: listOf(1, "two", 3.0, "four"). You want to create a new list containing only the strings using safe casts. Which Kotlin code correctly does this?
hard
A. val strings = list.mapNotNull { it as String? }
B. val strings = list.map { it as String }
C. val strings = list.filter { it is String }
D. val strings = list.map { it as? String }.filterNotNull()
Solution
Step 1: Understand the goal
We want to safely cast each element to String and keep only successful casts.
Step 2: Analyze options
val strings = list.map { it as? String }.filterNotNull() uses safe cast as? which returns null for non-strings, then filters out null values with filterNotNull(). This correctly produces a list of strings.
Step 3: Why others are incorrect
val strings = list.map { it as String } forces cast and will throw exception on non-strings. val strings = list.filter { it is String } filters by type but does not cast, so type is still Any. val strings = list.mapNotNull { it as String? } tries to cast with forced cast inside mapNotNull which will throw exception.
Final Answer:
val strings = list.map { it as? String }.filterNotNull() -> Option D
Quick Check:
Safe cast + filterNotNull = filtered strings [OK]
Hint: Use as? with filterNotNull to keep only successful casts [OK]
Common Mistakes:
Using forced cast causing exceptions
Filtering type without casting
Misusing mapNotNull with forced cast
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.