Industrial Training




Unsafe and Safe Cast


Sometime it is not possible to cast variable and it throws an exception, this is called as unsafe cast. The unsafe cast is performed by the infix operator as.
A nullable string (String?) cannot be cast to non nullabe string (String), this throw an exception.


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

The above program throw an exception:


Exception in thread "main" kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String  
 at TestKt.main(Test.kt:3)  
Exception in thread "main" kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String  
 at TestKt.main(Test.kt:3)  

While try to cast integer value of Any type into string type lead to generate a ClassCastException.


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

Source and target variable need to nullable for casting to work:


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

Output:
String unsafe cast

Kotlin Safe cast operator: as?


Kotlin provides a safe cast operator as? for safely cast to a type. It returns a null if casting is not possible rather than 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)  
}  
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


Hi I am Pluto.