How to destroy the list of Kotlin in the lists?

How can I destroy a list in Kotlin for two subscriptions? I am currently doing something like this:

val (first, rest) = listOf("one", "two", "three")

But at the same time, first “one” and “two”. I want them to be first =["first"]and rest = ["two", "three"].

Is this possible using this "destructor" syntax?

+4
source share
3 answers

Destructuring translates into function calls component1, component2etc. per object. In case a, Listthey are defined as extensions in the standard library and return the Nth element, respectively.


, Pair, :

fun <T> List<T>.split() = Pair(take(1), drop(1))

:

val (first, rest) = listOf("one", "two", "three").split()

println(first) // [one]
println(rest)  // [two, three]

, - , split , .

+3

:

operator fun <T> List<T>.component2(): List<T> = this.drop(1)

, :

val (head, rest) = listOf("one", "two", "three")
println(head) // "one"
println(rest) // ["two", "three"]
+3

This is possible by creating an operator component2as an extension method:

operator fun <T> List<T>.component2(): List<T> = drop(1)

fun destrcutList() {
    val (first: String, second: List<String>) = listOf("1", "2", "3")
}

You need to create an extension method only component2, component1to be used as before.

Types may be omitted:

fun destrcutList() {
    val (first, second) = listOf("1", "2", "3")
    println(second[0]) // prints "2"
}

One important note: if you declare an extension method in another package , you need to manually import the function :

import your.awesome.package.component2
+2
source

Source: https://habr.com/ru/post/1692109/


All Articles