Kotlin破坏了五个以上的组成部分 [英] Kotlin destructuring more than five components
问题描述
我得到了一个正则表达式的结果,该表达式将七个捕获组返回到一个数组中.
I have the result of a regex that returns seven capturing groups into an array.
问题是我似乎只能使用五个组件,而不是使用数组元素的下标来构造对象,我以为我会使用解构.
Rather than using the subscript of the array elements to construct my object I thought I would use destructuring, the problem is it seems I can only have five components.
一个最小的例子:
// 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
是否有一种方法可以包含五个以上的组件,或者这是最大值?
Is there a way to have more than five components or is this the max?
推荐答案
为 List
接口定义了5个组件功能(作为扩展功能).
There are only 5 component functions defined for the List
interface (as extension functions).
您可以添加自己的组件功能作为扩展功能:
You can add your own component functions as extension functions:
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)
来自文档:
当然,可以有component3()和component4()等等.
And, of course, there can be component3() and component4() and so on.
请注意,componentN()函数需要用运算符关键字,以允许在解构声明中使用它们.
Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.
这篇关于Kotlin破坏了五个以上的组成部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!