Swift 'if let' statement equivalent in Kotlin

iori24 picture iori24 · Oct 13, 2017 · Viewed 56.4k times · Source

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

if let a = b.val {

} else {

}

Answer

marstran picture marstran · Oct 13, 2017

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.