What is the difference between
x as? String
and
x as String?
They both seem to produce a String?
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.
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.