Swift 'if let' statement equivalent in Kotlin

前端 未结 14 1923
心在旅途
心在旅途 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:33

    Let's first ensure we understand the semantics of the provided Swift idiom:

    if let a =  {
         // then-block
    }
    else {
         // else-block
    }
    

    It means this: "if the results in a non-nil optional, enter the then-block with the symbol a bound to the unwrapped value. Otherwise enter the else block.

    Especially note that a is bound only within the then-block. In Kotlin you can easily get this by calling

    ?.also { a ->
        // then-block
    }
    

    and you can add an else-block like this:

    ?.also { a ->
        // then-block
    } ?: run {
        // else-block
    }
    

    This results in the same semantics as the Swift idiom.

提交回复
热议问题