Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `foo as? Foo` a complete equivalent of `foo as Foo?` in kotlin?

Tags:

kotlin

Is foo as? Foo a complete equivalent of foo as Foo? ?

If yes then why have both?

If no then what's the difference?

like image 257
guai Avatar asked Jan 03 '23 16:01

guai


1 Answers

as? is the safe cast operator.

Usually, if you try to cast a variable, and it fails, you get a ClassCastException. Using this operator, it just returns null instead in this case.

This means that the return type of the foo as? Foo expression is actually Foo?, because it might return null.


foo as Foo? is a cast of foo to the nullable Foo? type, this can still produce an exception if the variable isn't of that type (i.e. it's not a Foo instance or null).

like image 162
zsmb13 Avatar answered Jan 08 '23 06:01

zsmb13