Kotlin as vs as? : unsafe and safe cast operator (class cast exception)

2022. 5. 29. 13:43카테고리 없음

1. Kotlin cast operator

You can use 'as' to apply type casting. However, if the type can not be assigned to the specific target data, it receives the ClassCastException.

 

If you want to remove the exception, you should use 'as?' instead of the 'as' operator. This operator returns 'null' if the class cast exception occurs.

 

2. Unsafe operator 'as'

The operator 'as' can not assign data to unrelated data types. 

 

l CODE

fun main() {
    val charactername:Any = "Slowbook"
    val character: String?= charactername as? String
    println("here is your name : ${character}")
    
    val age: Int? = charactername as Int
    println("your age is : ${age}")
    
    
}

 

l EXPLANATION

 The variable 'charactername' contains String type of data, the variable 'character' can contain both null and String.

val charactername:Any = "Slowbook"
val character: String?= charactername as? String

 

 The variable 'age' can have Int data and null. However, chractername is String, which is unable to be assigned to the 'age'. This makes class cast exception.

val age: Int? = charactername as Int

 

l RESULT

l specific error sentences

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at FileKt.main (File.kt:6)
at FileKt.main (File.kt:-1)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2)

 

3. Safe operator 'as?'

The operator 'as?' returns null if the class cast exception occurs.

 

l CODE

fun main() {
    val charactername:Any = "Slowbook"
    val character: String?= charactername as? String
    println("here is your name : ${character}")
    
    val age: Int? = charactername as? Int
    println("your age is : ${age}")
    
    
}

the variable 'charactername' has String type, and the variable 'age' tries to regard it as Int type.

In this case, the unsafe operator may return cast error. However, safe operator 'as?' regarded the charactername as Null and assigned null into the variable 'age'. This was possible because the variable has 'Int?' type, which allows int and null type. 

 

l RESULT