Any better workaround for nullable destructuring? ...
# announcements
s
Any better workaround for nullable destructuring?
Copy code
val (p1,p2) = pair ?: null to null
a
You can make extensions:
Copy code
operator fun <T, V> Pair<T, V>?.component1(): T? = null
operator fun <T, V> Pair<T, V>?.component2(): V? = null

val (p1,p2) = pair
But that'd only work for pair for example. You've to redefine these things for triple, data classes, etc.
s
I reworked the code and ended up doing this instead:
Copy code
pair?.let { (p1,p2) -> 
}
2
But thanks
👍 2
i
That last line is a bit unreadable, I think. It is succinct, which is nice — but it’s not straightforward to read. do you need that snippet more than once in the codebase?
if yes, consider extracting the behavior to a function; otherwise, consider changing how you set the “pair” itself
(just like we don’t send back a list as null, but an empty list, a similar idiom may work here where you don’t send back a null pair, but a pair of nulls)
If the situation is recurrent, there’s a case for something like this in the codebase:
Copy code
inline fun <T>valueOrDefault(value:T?,default:T):T = value?:default
which is easy on the eyes on the calling site
n
?.let is a totally standard Kotlin idiom so I'm confused why you call it unreadable
i
the
.let {(p1,p2)-> }
is what I find harder to parse.
or, as I said it earlier — “a bit unreadable”
n
I dunno, it's really just two pretty standard things combined though, the ?.let and lambda destructuring 🤷
1
i
It’s OK if my point does not make sense to you.
👍 1