Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of `component1` to `component5` for Kotlin Collection?

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?

like image 558
Elye Avatar asked Sep 01 '25 02:09

Elye


1 Answers

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.

like image 118
gidds Avatar answered Sep 02 '25 22:09

gidds