0
0
Kotlinprogramming~20 mins

Safe casts with as? in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Safe Cast Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
Anull
BHello
CClassCastException
DCompilation error
Attempts:
2 left
💡 Hint
Safe cast returns the object if it matches the type, else null.
Predict Output
intermediate
2: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)
Anull
B123
CClassCastException
DCompilation error
Attempts:
2 left
💡 Hint
Safe cast returns null if the object is not of the target type.
🔧 Debug
advanced
2: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)
AClassCastException
BCompilation error
Cnull
DPrints 123
Attempts:
2 left
💡 Hint
Unsafe cast throws an exception if the cast is invalid.
Predict Output
advanced
2: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)
AClassCastException
BCompilation error
CEmpty string
Dnull
Attempts:
2 left
💡 Hint
Safe cast returns null if the object is null or not the target type.
🧠 Conceptual
expert
2: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?
ASafe cast improves performance by skipping type checks.
BSafe cast always converts the object to the target type regardless of its actual type.
CSafe cast returns null instead of throwing an exception if the cast fails, preventing runtime crashes.
DSafe cast automatically converts null values to default instances of the target type.
Attempts:
2 left
💡 Hint
Think about what happens when a cast fails.