Bird
Raised Fist0
Kotlinprogramming~10 mins

Safe casts with as? in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Safe casts with as?
Start with Any? variable
↓
Attempt safe cast with 'as?'
↓
Is cast possible?
No→Result is null
Yes↓
Result is casted value
↓
Use result
Try to convert a variable to a type safely. If it fits, get the value; if not, get null.
Execution Sample
Kotlin
val obj: Any = "Hello"
val str: String? = obj as? String
println(str)
Try to cast obj to String safely; print the result or null.
Execution Table
StepVariableActionEvaluationResult
1objAssign "Hello"obj is Any holding String"Hello"
2strSafe cast obj as? Stringobj is String, cast succeeds"Hello"
3printlnPrint strstr is "Hello"Output: Hello
💡 Execution ends after printing the casted string.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
objuninitialized"Hello""Hello""Hello"
struninitializeduninitialized"Hello""Hello"
Key Moments - 2 Insights
Why does 'str' become null if obj is not a String?
Because 'as?' tries to cast safely and returns null if the cast fails, as shown in step 2 of the execution_table.
What happens if we use 'as' instead of 'as?' and the cast fails?
The program throws a ClassCastException and stops, unlike 'as?' which returns null safely.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'str' after step 2?
Auninitialized
Bnull
C"Hello"
DClassCastException
💡 Hint
Check the 'Result' column in row for step 2 in execution_table.
At which step does the safe cast happen?
AStep 2
BStep 3
CStep 1
DNo safe cast
💡 Hint
Look at the 'Action' column in execution_table for the safe cast operation.
If obj was an Int instead of String, what would 'str' be after step 2?
A"Hello"
Bnull
CInt value
DClassCastException
💡 Hint
Recall that 'as?' returns null if cast fails, see key_moments explanation.
Concept Snapshot
Safe cast syntax: val x = y as? Type
Returns casted value if possible, else null.
Prevents exceptions from invalid casts.
Useful when unsure of variable type.
Always returns nullable type.
Full Transcript
This visual trace shows how Kotlin's safe cast operator 'as?' works. We start with a variable 'obj' holding a value of type Any. We try to cast it safely to String using 'as?'. If 'obj' is actually a String, the cast succeeds and 'str' holds the string value. Otherwise, 'str' becomes null. This prevents the program from crashing with a ClassCastException. The execution table shows each step: assigning obj, performing the safe cast, and printing the result. The variable tracker shows how 'obj' and 'str' change. Key moments clarify why 'str' can be null and the difference from unsafe casts. The quiz tests understanding of these steps and outcomes. The snapshot summarizes the safe cast usage and behavior.

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

  1. Step 1: Understand the safe cast operator

    The as? operator attempts to cast a value to a specified type safely.
  2. Step 2: Behavior on failure

    If the cast is not possible, instead of throwing an error, it returns null.
  3. Final Answer:

    It tries to cast a value to a type and returns null if it fails. -> Option C
  4. 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

  1. Step 1: Identify safe cast syntax

    In Kotlin, the safe cast operator is as? which tries to cast safely.
  2. Step 2: Match syntax to code

    The code val x = obj as? String attempts to cast obj to String safely.
  3. Final Answer:

    as? -> Option A
  4. 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

  1. Step 1: Analyze the cast attempt

    Variable obj holds an integer 123, but we try to cast it to String using safe cast as?.
  2. Step 2: Safe cast behavior

    Since obj is not a String, the safe cast returns null instead of throwing an error.
  3. Final Answer:

    null -> Option A
  4. 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

  1. Step 1: Analyze variable types and cast

    The safe cast obj as? Int returns null if cast fails, so the result is nullable Int?.
  2. Step 2: Fix type mismatch

    Declaring num as non-nullable Int causes a type mismatch error. Changing it to Int? fixes this.
  3. Final Answer:

    Change val num: Int to val num: Int? -> Option B
  4. 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

  1. Step 1: Understand the goal

    We want to safely cast each element to String and keep only successful casts.
  2. 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.
  3. 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.
  4. Final Answer:

    val strings = list.map { it as? String }.filterNotNull() -> Option D
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard