Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe cast vs cast to nullable

Tags:

kotlin

What is the difference between

x as? String

and

x as String?

They both seem to produce a String? type. The Kotlin page doesn't answer it for me.

UPDATE:

To clarify, my question is:

What is the purpose of having an as? operator at all, since for any object x and for any type T, the expression x as? T can be (I think) rephrased as x as T? ?

like image 563
DodgyCodeException Avatar asked Jun 13 '18 11:06

DodgyCodeException


People also ask

What is safe cast?

The point of the safe cast operator is safe casting. In the above example, I used the original String example with integers as the type. unsafeCast on an Int of course throws an exception, because an Int is not a String. safeCast does not, but res ends up as null.

What is safe cast in Kotlin?

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.

Which operator can safely cast a value in Kotlin?

"Safe" (nullable) cast operator.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


2 Answers

The difference lies in when x is a different type:

val x: Int = 1

x as String? // Causes ClassCastException, cannot assign Int to String?

x as? String // Returns null, since x is not a String type.
like image 109
Kiskae Avatar answered Sep 28 '22 10:09

Kiskae


as? is the safe type cast operator. This means if casting fails, it returns null instead of throwing an exception. The docs also state the returned type is a nullable type, even if you cast it as a non-null type. Which means:

fun <T> safeCast(t: T){
    val res = t as? String //Type: String?
}

fun <T> unsafeCast(t: T){
    val res = t as String? //Type: String?
}

fun test(){
    safeCast(1234);//No exception, `res` is null
    unsafeCast(null);//No exception, `res` is null
    unsafeCast(1234);//throws a ClassCastException
}

The point of the safe cast operator is safe casting. In the above example, I used the original String example with integers as the type. unsafeCast on an Int of course throws an exception, because an Int is not a String. safeCast does not, but res ends up as null.

The main difference isn't the type, but how it handles the casting itself. variable as SomeClass? throws an exception on an incompatible type, where as variable as? SomeClass does not, and returns null instead.

like image 20
Zoe stands with Ukraine Avatar answered Sep 28 '22 11:09

Zoe stands with Ukraine