I am bit confused regarding `as` and `as?`.. In t...
# getting-started
p
I am bit confused regarding
as
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?
d
as
casts and throws if impossible, so in your case you want
ref as String
.
as?
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.
Whether or not
ref
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)
p
wait so if I
ref
is
null
and I do
ref as String
it succeeds?
shouldnt it be
ref as String?
?
d
No. It does not succeed, it throws.
Because
null
is not a
String
p
what if I want to throw a different exception than
ClassCast
?
replace it with
if (ref is xyz)
?
d
That, or you can do
ref as? String ?: throw FooBarException()
p
but my ref is nullable!
i feel like i am going in circles here 😄
d
If you cast to
String
it no longer is.
p
but i want to allow it to be
null
d
Yes, then you need
if (ref is String?)
p
ok got it
thanks Take
d
(If you want a custom exception)
Ignore that.