(That is, what's the difference between `as? Strin...
# announcements
s
(That is, what's the difference between
as? String
and
as String?
? simple smile)
d
as? String
will try to cast to non-null String and give
null
if not possible (i.e. value is null or something other than String, such as Int).
as String?
will cast to nullable String and fail if it's something else (e.g. Int).
Fail being ClassCastException
s
But the end result of both operations will always be a
String?
(unless it fails because it's an
Int
or whatever)?
So something like this will not compile:
Copy code
("Hello World" as? String).length
Due to not checking for
null
first (i.e.
?.length
).
Oh!
Copy code
(1337 as? String) // => null
Alright, gotcha! Thanks, @diesieben07. simple smile
d
Yes,
1337 as? String
is null,
1337 as String?
throws
ClassCastException
s
Yep, that was the difference! TIL. simple smile