I'm trying to find out how to achieve the combination of "if let + cast" in kotlin:

in swift:

if let user = getUser() as? User {
   // user is not nil and is an instance of User
}

I saw some documentation but they say nothing regarding this combination

https://medium.com/@adinugroho/unwrapping-sort-of-optional-variable-in-kotlin-9bfb640dc709 https://kotlinlang.org/docs/reference/null-safety.html

推荐答案

一种 Select 是使用safe cast operator+safe call+let:

(getUser() as? User)?.let { user ->
    ...
}

Another would be to use a smart cast inside the lambda passed to let:

getUser().let { user ->
    if (user is User) {
        ...
    }
}

但也许最具可读性的方法是只引入一个变量,并在那里使用智能强制转换:

val user = getUser()
if (user is User) {
    ...
}

Kotlin相关问答推荐

Gradle Jooq配置自定义生成器

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

为什么 Kotlin 中没有 init 块的注释

仅某些用户出现 DateTimeFormatter 错误

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

如何避免键盘打开时jetpack compose 内容上升

嵌套数组 indexOf()

is return inside function definition 也是 kotlin 中的表达式

parallelStream()和asSequence().asStream().parallel()之间的区别

java - 如何将函数作为参数从java传递给kotlin方法?

Kotlin 协程中的 Dispatchers.Main 和 Dispatchers.Default 有什么区别?

如何退出 Kotlinc 命令行编译器

如何用 kotlin 打包 List

将 Firebase 数据快照反序列化为 Kotlin 数据类

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

大小写敏感性 Kotlin / ignoreCase

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

Kotlin lambda 语法混淆

Kotlin协程无法处理异常