如何将Kotlin列表拆成子列表?
我怎样才能把Kotlin中的一个表列成两个子列表呢? 目前我做这样的事情:
val (first, rest) = listOf("one", "two", "three")
但是这样做,首先是“一”,rest是“二”。 我希望他们是first =["first"]
和rest = ["two", "three"]
。
这甚至可以使用这个“析构函数”语法?
解构意味着在对象上调用component1
, component2
等操作符函数。 在List
的情况下,它们被定义为标准库中的扩展 ,并分别返回第N个元素。
你可以定义你自己的扩展扩展,根据需要分割列表并返回一个Pair
,然后可以解构它:
fun List .split() = Pair(take(1), drop(1))
这可以像这样使用:
val (first, rest) = listOf("one", "two", "three").split() println(first) // [one] println(rest) // [two, three]
也许命名比split
更好,但是会很聪明。
你也可以定义你自己的组件function:
operator fun List .component2(): List = this.drop(1)
然后,按预期工作:
val (head, rest) = listOf("one", "two", "three") println(head) // "one" println(rest) // ["two", "three"]
可以通过手动创建component2
运算符作为扩展方法:
operator fun List .component2(): List = drop(1) fun destrcutList() { val (first: String, second: List) = listOf("1", "2", "3") }
您只需要为component2
创建扩展方法,将使用component1
。
types可以省略:
fun destrcutList() { val (first, second) = listOf("1", "2", "3") println(second[0]) // prints "2" }
一个重要的注意事项:如果您在另一个包中声明扩展方法,则必须手动导入函数 :
import your.awesome.package.component2