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:
- Declare a nullable variable with ? to store the value
- Add a safe call with the as operator as ?
If the type casting is successful, it will return the original value. If not, it will become null. Let's take a look at the correct way to use the as operator in the following example:
fun myUnsafeCast(any : Any?){
val s : String? = any as? String
println(s)
}
fun main (args: Array<String>) {
myUnsafetCast(2)
}
This time, the program will execute normally without throwing any exceptions. Instead, it will display null on the screen.