0
0
Kotlinprogramming~5 mins

Safe casts with as? in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Anull
BThrows ClassCastException
CThe integer value
DEmpty string
Which operator in Kotlin safely casts a value and returns null if it fails?
Aas?
Bas
Cis
D!!
What happens if you use as to cast an incompatible type?
AReturns null
BReturns default value
CThrows ClassCastException
DCompiles but ignores cast
Which of these is a benefit of using as??
AForces non-null values
BImproves performance by skipping checks
CAutomatically converts types
DAvoids program crashes on bad casts
If val y = obj as? String and y is null, what does that mean?
AThe cast succeeded
B<code>obj</code> was not a String
C<code>obj</code> was a String
DThe program crashed
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.