Unsafe and Safe Cast Operator in Kotlin

Unsafe cast operator: as

Sometime it’s not possible to cast variable associate degreed it throws an exception, this is often called as unsafe cast. The unsafe cast is performed by the infix operator as.

A nullable string can’t be cast to a non-nullabe string, this throws associate degree exception.

fun main(args: Array<String>){  
val obj: Any? = null  
val str: String = obj as String  
println(str)  
 }

The on top of program throw an exception:

Exception in thread "main" kotlin.TypeCastException: null can't be cast to non-null sort kotlin.String
at TestKt.main(Test.kt:3)

whereas attempt to cast number price of Any type into string sort cause generate a ClassCastException.

val obj: Any = 123
val str: String = obj as String
// Throws java.lang.ClassCastException: java.lang.Integer can't be cast to java.lang.String

Source and target variable have to be compelled to nullable for casting to work:

fun main(args: Array<String>){
val obj: String? = "String unsafe cast"
val str: String? = obj as String?
println(str)
}

Output:

String unsafe cast

Kotlin Safe cast operator: as?

Kotlin provides a safe cast operator as? for safely cast to a kind. It returns a null if casting isn’t potential instead of throwing AN ClassCastException exception.

Let’s see an example, trying to cast Any type of string value which is initially known by programmer not by compiler into nullable string and nullable int. It cast the value if possible or return null instead of throwing exception even casting is not possible.

fun main(args: Array<String>){  
  
val location: Any = "Kotlin"  
val safeString: String? = location as? String  
val safeInt: Int? = location as? Int  
println(safeString)  
println(safeInt)  
}  

Output:

Kotlin
null

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories