Kotlin的`as有什么不同?类型`与`作为类型?`
下面是一段代码
val firstAny: Any? = someVariable as? Any
val secondAny: Any? = someVariable as Any?
对我来说,看起来两者都会产生相同的结果。它们之间有什么区别,即as? Typevs as Type??
回答
因为Any?它们是等价的。
如果您要转换为另一种类型,则当该类型无法转换时:
someVariable as? Type会回来null,但是someVariable as Type?将失败ClassCastException。