August 2018
Beginner
178 pages
4h 56m
English
There is also the safe casting operator, as?. This operator checks, before casting, whether or not types are compatible. If they are, then it works as a normal asoperator. If not, a null value is assigned. Notice how in this example, the local variable num has to be declared as a nullable type:
fun safeCasting(any: Any) { val num: Int? = any as? Int}
Safe casts can be used with all other null handling operators (safe call, non-null assertions, and Elvis), but Elvis is probably the most useful one. Together they can be used to do a non-null try-cast operation, like this example shows:
fun safeCastingWithElvisl(any: Any) { val num: Int = any as? Int ?: 0}
Read now
Unlock full access