Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destruct a Kotlin list into sublists?

Tags:

list

kotlin

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?

like image 235
Ueli Hofstetter Avatar asked Jan 12 '18 18:01

Ueli Hofstetter


People also ask

How do you Destructure an array in Kotlin?

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.

What is listOf in Kotlin?

The listOf() method in Kotlin is used to create an immutable list. An immutable list is read-only.

What is destruction in Kotlin?

Destructuring declarations is a Kotlin feature that gives you a tool for easily extracting data from a collection in a simple and clean way.

What is Destructuring in Kotlin?

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.


2 Answers

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.

like image 109
zsmb13 Avatar answered Oct 03 '22 04:10

zsmb13


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"]
like image 28
Todd Avatar answered Oct 03 '22 02:10

Todd