Kotlin Safe Casting as? Operator Tutorial

In this section, we will learn what the safe casting is and how to use it in Kotlin.

Safe Casting and the as? operator in Kotlin

In the Kotlin as operator section we mentioned that the as operator is used to cast an object explicitly to another type.

But the problem of using the as operator is that if the target object wasn’t of the specified type that we set for the as operator, then it will return an exception of type ClassCastException.

Now to solve this problem, Kotlin has provided the safe cast operator as? by which we can first check the type of the cast (that we want the object to be cast into) and if they matched and the operation was possible, in that case only the cast happens. Otherwise, if the casting wasn’t possible, the value null will return instead.

So using the safe cast operator, we can stop the throw of exception in case the types didn’t match and get a null value instead.

Example: using safe casting in Kotlin

open class Person {
    var firstName:String = "John"
    var lastName:String = "Doe"
}

class Employee:Person(){
    var company:String = "Apple"
}

fun main(){
    var person:Person = Employee()

    var emp = person as? Employee

    println(emp?.company)
}

Output:

Apple

How does safe casting work in Kotlin?

In the statement: var emp = person as? Employee we use the safe cast operator to cast the object that the person variable was pointing at into the Employee class type.

Now, because the safe cast operator might return a null value, then the value of the emp variable is of nullable type! This means we can use the safe call operator to first check and see if the value of the emp variable is null or not and if the value wasn’t null then in that case only we call its members like the way we did in this statement:

println(emp?.company)
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies