Swift 'if let' 语句在 Kotlin 中等效 [英] Swift 'if let' statement equivalent in Kotlin

查看:32
本文介绍了Swift 'if let' 语句在 Kotlin 中等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Kotlin 中是否有与下面的 Swift 代码等效的代码?

In Kotlin is there an equivalent to the Swift code below?

if let a = b.val {

} else {

}

推荐答案

你可以像这样使用 let 函数:

You can use the let-function like this:

val a = b?.let {
    // If b is not null.
} ?: run {
    // If b is null.
}

请注意,只有在需要代码块时才需要调用 run 函数.如果在 elvis-operator (?:) 之后只有一个单行,您可以删除 run-block.

Note that you need to call the run function only if you need a block of code. You can remove the run-block if you only have a oneliner after the elvis-operator (?:).

请注意,如果 b 为 null,或者 let-block 的计算结果为 run 块将被评估null.

Be aware that the run block will be evaluated either if b is null, or if the let-block evaluates to null.

因此,您通常只需要一个 if 表达式.

Because of this, you usually want just an if expression.

val a = if (b == null) {
    // ...
} else {
    // ...
}

在这种情况下,else-block 只会在 b 不为 null 时被评估.

In this case, the else-block will only be evaluated if b is not null.

这篇关于Swift 'if let' 语句在 Kotlin 中等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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