Reputation: 50
is it possible to reformat this piece of code in Kotlin, that it gets a bit smaller? The function should return A and B as a Pair, if both are unequal to null. Else it should return null. My first idea was like this:
private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? =
if (a != null && b != null)
a to b
else
null
Then I decided to use the Elvis Operator. So it now looks like this:
private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? {
a ?: return null
b ?: return null
return a to b
}
But what I am looking for is just something like this:
private fun <A, B> zip(a: A?, b: B?): Pair<A, B>? =
// This code obviously doesn't compile but is their any way to do it similar to this?
a, b ?: return null
return a to b
Thanks in advance!
Upvotes: 0
Views: 196
Reputation: 18537
One fairly concise option is to create the Pair and then filter it:
(a to b).takeIf{ a != null && b != null }
But this isn't very good: it'll sometimes create a Pair unnecessarily, and the result type will have the Pair params both nullable, even though you know they can't be.
You could write an extension function to make it simpler.
Otherwise, I don't think you can do better than:
if (a != null && b != null) a to b else null
which is slightly longer-winded but has better efficiency and stricter typing.
Upvotes: 3