October 2018
Intermediate to advanced
370 pages
9h 15m
English
The as operator is another method of type casting, but it is not considered a safe cast. Check out the following example of an unsafe cast:
fun myUnsafeCast(any : Any?) { val s : String = any as String println(s)}fun main (args: Array<String>) { myUnsafetCast("Hello")}
This code will execute successfully because a string variable is passed to this function, but the following function calls will throw a TypeCastException:
myUnsafetCast(2)myUnsafetCast(null)
It is very important to secure our code before it crashes, so try to avoid unsafe casting. However, if it is necessary, do the following:
If the type casting is successful, it will ...
Read now
Unlock full access