Recall & Review
beginner
What does the safe cast operator
as? do in Kotlin?It tries to cast a value to a specified type. If the cast is not possible, it returns
null instead of throwing an exception.Click to reveal answer
beginner
How is
as? different from the regular as cast in Kotlin?as throws a ClassCastException if the cast fails, while as? returns null safely without crashing the program.Click to reveal answer
beginner
What will be the result of
val x: String? = obj as? String if obj is an Int?The result will be
null because obj cannot be safely cast to String.Click to reveal answer
intermediate
Why is using
as? useful in Kotlin programming?It helps avoid program crashes by safely handling type casts that might fail, making code more robust and easier to maintain.
Click to reveal answer
beginner
Write a simple Kotlin code snippet using
as? to safely cast an Any type to String.val obj: Any = 123
val str: String? = obj as? String
println(str) // prints null because obj is not a String
Click to reveal answer
What does
val x = obj as? String return if obj is an Int?✗ Incorrect
as? returns null if the cast fails instead of throwing an exception.Which operator in Kotlin safely casts a value and returns null if it fails?
✗ Incorrect
as? is the safe cast operator that returns null on failure.What happens if you use
as to cast an incompatible type?✗ Incorrect
The regular
as operator throws a ClassCastException if the cast is invalid.Which of these is a benefit of using
as??✗ Incorrect
as? avoids crashes by returning null instead of throwing exceptions.If
val y = obj as? String and y is null, what does that mean?✗ Incorrect
Null means the cast failed because
obj was not of type String.Explain how the safe cast operator
as? works in Kotlin and why it is useful.Think about what happens when a cast might fail.
You got /3 concepts.
Write a Kotlin example using
as? to safely cast an Any variable to a String and handle the null case.Try to cast and then check if the result is null before using it.
You got /3 concepts.