In Kotlin document https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/component1.html
There's component1
till component5
. I'm a little lost what are the use cases of them?
I thought we could essentially mylist.get[0]
for mylist.component1
. It is shorter and more extensible.
It seems redundant to have such component1
etc. Did I miss out any detail?
These allow destructuring declarations.
Further down the page linked in the question, it explains that the corresponding component1()
and component2()
methods for Map entries allow you to use destructuring declarations with them. It's the same for collections and arrays.
If you need the first few elements of a collection, you can assign them to named variables like this:
val (first, second, third, fourth, fifth) = myList;
Similarly, if you pass a collection as a lambda parameter, it can split it easily:
myList.let{ (first, second, third) ->
// …
}
This feature is a little less useful for collections and arrays than it is for data classes or maps, as there's no guarantee that it's long enough; the above would give an IndexOutOfBoundsException
if not. Or if it's longer, the excess elements are ignored. But in cases where you can be sure of the length, it can be a little more concise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With