安全类型转换与可空值转换 [英] Safe cast vs cast to nullable

查看:53
本文介绍了安全类型转换与可空值转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别

x as? String

x as String?

它们似乎都产生一个String?类型. 科特琳页面不能为我回答.

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

更新:

为了澄清,我的问题是:

To clarify, my question is:

完全具有as?运算符的目的是什么,因为对于任何对象x和任何类型T,表达式(c4>都可以(我认为)改写为x as T?吗? /p>

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? ?

推荐答案

区别在于x是其他类型时:

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.

这篇关于安全类型转换与可空值转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆