Safe cast vs cast to nullable

后端 未结 2 1461
感情败类
感情败类 2021-01-11 11:52

What is the difference between

x as? String

and

x as String?

They both seem to produce a String?

相关标签:
2条回答
  • 2021-01-11 12:29

    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.

    0 讨论(0)
  • 2021-01-11 12:46

    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.
    
    0 讨论(0)
提交回复
热议问题