https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Alexander Suraphel

08/24/2021, 4:34 PM
What is the difference between
*val* x: String? = y *as* String?
and
*val* x: String? = y *as*? String
?
r

Richard Gomez

08/24/2021, 4:34 PM
With
as
, if y cannot be safely cast to
String
it will throw an exception. With
as?
, it will simply return null.
👍 4
c

CLOVIS

08/24/2021, 4:53 PM
*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

Alexander Suraphel

08/24/2021, 4:57 PM
Thanks guys! I understand the distinction now.
2 Views