Kotlin Explicit Type Casting

Kotlin explicit casting works on is or ! is an operator check variable and the compiler automatically casts the variable, but in explicit type casting, we used it as an operator.

 1. Unsafe cast operator: as

 2. Safe cast operator: as?

Unsafe cast operator: as

We use the cast operator to cast a variable to another type.

fun main(args: Array<String>){

val str1: String = "Hello, how are you ?"

val str2: String = str1 as String 

println(str1)

}

Output

Hello, how are you?

 

The above example str1 variable is a string to convert type using as operator and converted value store in the str2 variable.

There might be a possibility of not casting value while executing code throws an exception unsafe casting.

Example 1:


fun main(args: Array<String>){

    val str1: Any = 34

    val str2: String = str1 as String  // throw exception

    println(str1)

}

 

Output

Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')

The above example str1 is Int but converted into the string so throw an exception.

Example 2:

We can not cast a nullable string to a non-nullable string.

fun main(args: Array<String>){

val str1: String? = null

val str2: String = str1 as String // throw exception

println(str1)

}

Output

Exception in thread "main" java.lang.NullPointerException: null cannot be cast to non-null type kotlin.String

 

Safe cast operator: as?

Kotlin also provides facilities to safe cast operators as? If casting is not possible it returns null instead of throwing a  Class castexception.

fun main(args: Array<String>){

var str1: Any = "Safe casting example"

val str2: String? = str1 as? String // it works

str1 = 35

 

val str3: String? = str1 as? String

val str4: Int? = str1 as? Int // it works

println(str2)

println(str3)

println(str4)

}

Output

Safe casting example

null

35

Happy Coding!


365Bloggy May 8, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive