poohbar
06/12/2019, 2:31 PMas
and as?
..
In this example ref as? String
the result is null
if the ref
is not a String
or if the ref
is null, correct?
I need to cast a reference to String and throw if it is not a String. How can I do that?diesieben07
06/12/2019, 2:31 PMas
casts and throws if impossible, so in your case you want ref as String
.diesieben07
06/12/2019, 2:32 PMas?
tries to cast and returns null otherwise, so ref as? String
will be null
if ref
wasn't a String
and ref
if it was.diesieben07
06/12/2019, 2:33 PMref
was null
is only remotely relevant in that null
is not a String
, so as
would throw and as?
would give you null
(because the cast failed)poohbar
06/12/2019, 2:34 PMref
is null
and I do ref as String
it succeeds?poohbar
06/12/2019, 2:34 PMref as String?
?diesieben07
06/12/2019, 2:35 PMdiesieben07
06/12/2019, 2:35 PMnull
is not a String
poohbar
06/12/2019, 2:36 PMClassCast
?poohbar
06/12/2019, 2:36 PMif (ref is xyz)
?diesieben07
06/12/2019, 2:37 PMref as? String ?: throw FooBarException()
poohbar
06/12/2019, 2:37 PMpoohbar
06/12/2019, 2:37 PMdiesieben07
06/12/2019, 2:37 PMString
it no longer is.poohbar
06/12/2019, 2:37 PMnull
diesieben07
06/12/2019, 2:38 PMif (ref is String?)
poohbar
06/12/2019, 2:38 PMpoohbar
06/12/2019, 2:38 PMdiesieben07
06/12/2019, 2:38 PMdiesieben07
06/12/2019, 2:38 PM