October 2021
Intermediate to advanced
500 pages
16h 23m
English
Earlier in this chapter, we introduced the as operator as a mechanism for performing casting. We also mentioned that type casting in this way is sometimes deemed unsafe and can lead to ClassCastExceptions if you perform an invalid cast when your program runs.
In addition to the as operator, there is also a safe cast operator, which is as?. as? behaves very similarly to as, but with one key difference: If you perform an invalid cast, as? returns null instead of throwing an exception. Try it out for yourself in the REPL:
Listing 15.26 Safe and unsafe casting (REPL)
5 as String ClassCastException: class Integer cannot be cast to class String 5 as? String null
as? is a great way ...
Read now
Unlock full access