What is the difference between `*val* x: String? =...
# getting-started
a
What is the difference between
*val* x: String? = y *as* String?
and
*val* x: String? = y *as*? String
?
r
With
as
, if y cannot be safely cast to
String
it will throw an exception. With
as?
, it will simply return null.
👍 4
c
*safely cast to
String?
as String?
Crashes for everything that isn't a
String
or
null
,
as? String
Accepts any value, returns a
String
if it is one,
null
otherwise.
(both allow
null
)
If you don't want
null
, the solution is to use
as String
, which will crash for any
non-String
value (even
null
)
a
Thanks guys! I understand the distinction now.