Challenge - 5 Problems
Safe Cast Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of safe cast with as? when cast succeeds?
Consider the following Kotlin code using safe cast
as?. What will be printed?Kotlin
val obj: Any = "Hello" val str: String? = obj as? String println(str)
Attempts:
2 left
💡 Hint
Safe cast returns the object if it matches the type, else null.
✗ Incorrect
The variable obj holds a String. Safe cast
as? tries to cast obj to String. Since obj is already a String, the cast succeeds and str holds "Hello". So printing str outputs Hello.❓ Predict Output
intermediate2:00remaining
What is the output of safe cast with as? when cast fails?
What will this Kotlin code print?
Kotlin
val obj: Any = 123 val str: String? = obj as? String println(str)
Attempts:
2 left
💡 Hint
Safe cast returns null if the object is not of the target type.
✗ Incorrect
obj holds an Int, but we try to cast it safely to String. Since it is not a String, the safe cast returns null. So printing str outputs null.
🔧 Debug
advanced2:00remaining
Identify the error in unsafe cast without as? operator
What error will this Kotlin code produce at runtime?
Kotlin
val obj: Any = 123 val str: String = obj as String println(str)
Attempts:
2 left
💡 Hint
Unsafe cast throws an exception if the cast is invalid.
✗ Incorrect
The code uses unsafe cast
as to cast an Int to String. This is invalid and causes a ClassCastException at runtime.❓ Predict Output
advanced2:00remaining
What is the output when safe cast is used with a nullable type?
What will this Kotlin code print?
Kotlin
val obj: Any? = null val str: String? = obj as? String println(str)
Attempts:
2 left
💡 Hint
Safe cast returns null if the object is null or not the target type.
✗ Incorrect
obj is null. Safe cast
as? returns null when casting null to any type. So str is null and printing it outputs null.🧠 Conceptual
expert2:00remaining
Why use safe cast (as?) instead of unsafe cast (as)?
Which of the following best explains the advantage of using safe cast
as? over unsafe cast as in Kotlin?Attempts:
2 left
💡 Hint
Think about what happens when a cast fails.
✗ Incorrect
Safe cast
as? returns null if the object cannot be cast to the target type, avoiding exceptions and crashes. Unsafe cast as throws ClassCastException on failure.