How to idiomatically unwrap multiple optionals (wi...
# announcements
i
How to idiomatically unwrap multiple optionals (without nesting)?
r
Create a function that does it
i
ok... I guess just
if (a != null && b != null) {...}
is enough, because of smart cast
ah right but that works only if I assigned vals already. Not e.g. retrieving values of a map
n
You could do something like this
Copy code
fun example () {
	var a: Double? = null
	var b: Double? = null
	(a and b)?.let { (a, b) -> { /* Your function */ } }
}

infix fun Any?.and (other: Any?): Pair<Any, Any>? {
	return if (this != null && other != null) this to other else null
}
If you didn't want to rely on type casting, you could add generics, though it makes using an infix function a little less attractive. Now the types of both parameters are known:
Copy code
fun example () {
	var a: Double? = null
	var b: Double? = null
	safeCombine(a, b)?.let { (a, b) -> { /* Your function */ } }
}

fun<A, B> safeCombine (a: A?, b: B?): Pair<A, B>? {
	return if (a != null && b != null) a to b else null
}
Can mess around with this sort of implementation to get your desired effect I think? If they variables were all the same type you could expand it to use
vararg
and return a null safe collection
i
@ndv thanks! for more than 2 pars
vararg
and list is not ideal though... but cool input nonetheless