When making a safe cast on an object that might be...
# announcements
m
When making a safe cast on an object that might be null, is there a difference between
val casted = nullable as? String
and
val casted = nullable as String?
? They both smart cast to
String?
but do they both give null if
nullable
is null and
nullable
casted to a string (assuming the cast is possible)? I know using
as?
returns null if the cast fails and i assume option 2 would throw an exception, is that the only difference?
r
Yes, the first will return null if nullable isn't a String or null, the second will throw an exception.
Copy code
5 as String?  // error
5 as? String  // null
null as String?  // null
null as? String  // null
null as String  // error
👍 7
💯 3