Swift 'if let' statement equivalent in Kotlin

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

    To unwrap multiple variables at once like in the Swift if let syntax you may consider a global utility function along the following lines (example takes 3 parameters, but you can define overloads for any number of parameters):

    inline fun <A : Any, B : Any, C : Any> notNull(
        a: A?, b: B?, c: C?, perform: (A, B, C) -> Unit = { _, _, _ -> }
    ): Boolean {
        if (a != null && b != null && c != null) {
            perform(a, b, c)
            return true
        }
        return false
    }
    

    Sample usage:

    if (notNull("foo", 1, true) { string, int, boolean ->
        print("The three values were not null and are type-safe: $string, $int, $boolean")
    }) else {
        print("At least one of the vales was null")
    }
    
    0 讨论(0)
  • 2020-12-02 08:33

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

    if let a = <expr> {
         // then-block
    }
    else {
         // else-block
    }
    

    It means this: "if the <expr> 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

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

    and you can add an else-block like this:

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

    This results in the same semantics as the Swift idiom.

    0 讨论(0)
提交回复
热议问题