Bird
0
0

Which of the following is a valid use of the safe cast operator as? in Kotlin?

easy📝 Conceptual Q2 of 15
Kotlin - Null Safety

Which of the following is a valid use of the safe cast operator as? in Kotlin?

Aval num: Int = obj as? Int
Bval num: Int? = obj as? Int
Cval num: Int = obj as Int?
Dval num: Int = obj as Int
Step-by-Step Solution
Solution:
  1. Step 1: Check type compatibility with safe cast

    The safe cast as? returns a nullable type, so the variable must accept nulls.
  2. Step 2: Analyze options

    Only val num: Int? = obj as? Int declares a nullable Int, matching the safe cast's nullable return type.
  3. Final Answer:

    val num: Int? = obj as? Int -> Option B
  4. Quick Check:

    Safe cast returns nullable type = B [OK]
Quick Trick: Safe cast result must be nullable type variable [OK]
Common Mistakes:
MISTAKES
  • Assigning safe cast result to non-nullable variable
  • Using unsafe cast syntax with safe cast operator
  • Confusing nullable and non-nullable types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes