Swift 'if let' statement equivalent in Kotlin

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.


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.

Tags:

Kotlin