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