gpt4 book ai didi

Kotlin 解构超过五个组件

转载 作者:行者123 更新时间:2023-12-01 23:03:24 25 4
gpt4 key购买 nike

我有一个正则表达式的结果,它将七个捕获组返回到一个数组中。

我认为我会使用解构而不是使用数组元素的下标来构造我的对象,但问题是我似乎只能有五个组件。

一个最小的例子:

//  val (a, b, c, d, e) = listOf(1, 2, 3, 4, 5)
val (a, b, c, d, e, f, g) = listOf(1, 2, 3, 4, 5, 6, 7)

编译器输出:
> Error:(70, 41) Kotlin: Destructuring declaration initializer of type
> List<Int> must have a 'component6()' function
> Error:(70, 41) Kotlin: Destructuring declaration initializer of type
> List<Int> must have a 'component7()' function

有没有办法拥有五个以上的组件,或者这是最大的?

最佳答案

List 只定义了 5 个组件函数。接口(interface)(作为扩展功能)。

您可以添加自己的组件函数作为扩展函数:

operator fun <T> List<T>.component6() = this[5]
operator fun <T> List<T>.component7() = this[6]
// ...

这现在可以工作了:
val (a, b, c, d, e, f, g) = listOf(1, 2, 3, 4, 5, 6, 7)

来自 docs :

And, of course, there can be component3() and component4() and so on.

Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.

关于Kotlin 解构超过五个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com