Is it possible to destruct a list into variables e...
# announcements
s
Is it possible to destruct a list into variables e.g.
Copy code
val item1, item2, item3 = list
If so, is it possible to make it do a getOrNull?
a
Do you mean, if you try to destructure more items than are in the list, get null?
s
Well that too. But primarily about item1 = list[0], item2 = list[1], etc.
or more specifically list.getOrNull(0), etc.
k
val (item1, item2, item3) = list
, works up to 5 elements IIRC.
👍 1
a
hmm well you can destructure the way you have it written, but if you ask for more items than are in the list it won't work.
👍 1
s
ahh, alright
a
Also yes, limit of 5 as Karel said
k
Another idea, create a wrapper object with other
componentN
functions that return
null
instead:
val (item1, item2, item3) = list.destructOrNull()
👍 1
s
whats the method that destructs?
a
Also, if you need more than 5 for your specific use case and really wanna destructure, you can write an extension method for the remaining componentN methods. It becomes a nuisance if you have a lot, but if you wanna go up to 6 you can do this:
Copy code
operator fun <T> List<T>.component6(): T {
    return this[5]
}
s
oh, i get it. Thank you!
k
destructOrNull
would return an instace of something like
class ListDestructorWrapper
that has those functions defined on it.