How can I destruct a list in Kotlin into two sublists? Currently I do something like this:
val (first, rest) = listOf("one", "two", "three")
But doing so, first is "one" and rest is "two". I want them to be first =["first"]
and rest = ["two", "three"]
.
Is this even possible using this "destructor" syntax?
If you want to skip a variable or element in destructuring declarations, then you can use underscore instead of the variable name. As a result, Kotlin won't call the component function for those unused variables. For example, we need only the 1st, 5th and 6th elements in the array.
The listOf() method in Kotlin is used to create an immutable list. An immutable list is read-only.
Destructuring declarations is a Kotlin feature that gives you a tool for easily extracting data from a collection in a simple and clean way.
A destructuring declaration creates multiple variables at once. You have declared two new variables: name and age , and can use them independently: println(name) println(age) A destructuring declaration is compiled down to the following code: val name = person.
Destructuring translates to calling component1
, component2
, etc. operator functions on an object. In the case of a List
, these are defined as extensions in the standard library, and return the Nth element respectively.
You could define your own extension extension that splits the list as desired and returns a Pair
, which can then be destructured:
fun <T> List<T>.split() = Pair(take(1), drop(1))
This could be used like so:
val (first, rest) = listOf("one", "two", "three").split()
println(first) // [one]
println(rest) // [two, three]
Perhaps naming it something better than split
would be smart though.
You could also define your own component functions:
operator fun <T> List<T>.component2(): List<T> = this.drop(1)
And then this works as expected:
val (head, rest) = listOf("one", "two", "three")
println(head) // "one"
println(rest) // ["two", "three"]
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