In Kotlin is there an equivalent to the Swift code below?
if let a = b.val {
} else {
}
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.