Left Index

Unsafe and Safe Cast Operator

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.


When working with mixed types, We often need to know the type of an object at runtime so that we can safely cast the object to our desired type and call methods or access properties on it. In Smart Casting, we generally use is or !is operator to check the type of variable, and compiler automatically casts the variable to the target type, but in explicit type casting we use as operator.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val obj: Any? = "Welcome The It Bulls Kotlin Tutorial"  
	val str: String = obj as String  
	println(str)  
}
Output:
Welcome The It Bulls Kotlin Tutorial

Unsafe Casting

There might be possibility that we can not cast variable to target type and it throws an exception at runtime, that is why it is called as unsafe casting. When Integer type is used to cast to String type, then it throws ClassCastException. For example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val obj: Any? = 42  
	val str: String = obj as String  
	println(str)  
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at com.theitbulls.kotlinex.HelloWorldKt.main(HelloWorld.kt:5)

Note: We can not cast a nullable string to non-nullabe string, and it throws an exception TypeCastException.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val obj: String = null 
	// below line will throw i.e. kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String
	val str: String = obj as String  
	println(str)  
}

So to resolve above problem, we have to use target type also as nullable String so that type casting throws no exception.

Example:
package com.theitbulls.kotlinex

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

Safe cast operator: as?

Kotlin also provides a facility of type casting using safe cast operator as?. If casting is not possible it returns null instead of throwing an ClassCastException exception.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var obj: Any = "Welcome The It Bulls Kotlin Tutorial" 
	var msg1: String = obj as String
	
	var obj1: Int = 33
	
	// here type casting is not possible, so it return null to msg2
	var msg2: String? = obj1 as? String
	
	var msg3: Int? = obj1 as? Int
	  
	println(msg1)  
	println(msg2)  
	println(msg3)  
}
Output:
Welcome The It Bulls Kotlin Tutorial
null
33