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

查看:64
本文介绍了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函数.如果猫王操作员(?:)之后只有一个衬板,则可以删除run-块.

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为空,或者let-块的评估结果为null,将对run块进行评估.

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 {
    // ...
}

在这种情况下,仅当b不为null时,才会评估else -block.

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

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

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