Safe cast vs cast to nullable

后端 未结 2 1464
感情败类
感情败类 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: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.
    

提交回复
热议问题