Is there any way to chain multiple lets for multiple nullable variables in kotlin?
fun example(first: String?, second: String?) {
first?.let {
se
I actually prefer to solve it using the following helper functions:
fun T(tuple: Pair): Pair? =
if(tuple.first == null || tuple.second == null) null
else Pair(tuple.first!!, tuple.second!!)
fun T(tuple: Triple): Triple? =
if(tuple.first == null || tuple.second == null || tuple.third == null) null
else Triple(tuple.first!!, tuple.second!!, tuple.third!!)
fun T(first: A?, second: B?): Pair? =
if(first == null || second == null) null
else Pair(first, second)
fun T(first: A?, second: B?, third: C?): Triple? =
if(first == null || second == null || third == null) null
else Triple(first, second, third)
And here's how you should use them:
val a: A? = someValue
val b: B? = someOtherValue
T(a, b)?.let { (a, b) ->
// Shadowed a and b are of type a: A and b: B
val c: C? = anotherValue
T(a, b, c)
}?.let { (a, b, c) ->
// Shadowed a, b and c are of type a: A, b: B and c: C
.
.
.
}