Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1949
心在旅途
心在旅途 2020-12-02 07:32

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

if let a = b.val {

} else {

}
14条回答
  •  天命终不由人
    2020-12-02 08:30

    You can use the let-function like this:

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

    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 (?:).

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

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

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

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

提交回复
热议问题