kotlin as 和 is 的使用

kotlin 中有类型检测与类型转换章节,今天回顾看到这里记录下 详细的地址如下

类型检测与类型转换 · Kotlin 官方文档 中文版

as 的功能是类型转换

复制代码
val x: String = y as String

这个y就是String 类型,不过,这个写法可能存在问题,

as转换类型的时候null 不能转换,所以当y为null的时候就报错了

这个时候可以在as 后面添加 ?

复制代码
val x: String? = y as? String

as 是"不安全的"类型的转换

as?是"安全的"类型转换

is 的功能是类型检测

复制代码
fun demo(x: Any) {
    if (x is String) {
        print(x.length) // x 自动转换为字符串
    }
}
相关推荐
阿巴斯甜19 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker20 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952721 小时前
Andorid Google 登录接入文档
android
黄林晴1 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿2 天前
Android MediaPlayer 笔记
android
Jony_2 天前
Android 启动优化方案
android
阿巴斯甜2 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇2 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android