To cast from one type to another, Kotlin uses the as
keyword. Here’s how you would cast Any
type to an Int
type:
fun casting(any: Any) { val num = any as Int }
During runtime, before casting, the JVM will check if the source type can be cast to target type. If not, ClassCastException
will be thrown.
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 as
operator. 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 }