iex
01/15/2020, 3:22 PMribesg
01/15/2020, 3:25 PMiex
01/15/2020, 3:26 PMif (a != null && b != null) {...}
is enough, because of smart castiex
01/15/2020, 3:27 PMndv
01/15/2020, 9:23 PMfun 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:
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 collectioniex
01/16/2020, 5:32 PMvararg
and list is not ideal though... but cool input nonetheless