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.
A minimal example:
// 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)
Compiler output:
> 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?
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]
// ...
This would work now:
val (a, b, c, d, e, f, g) = listOf(1, 2, 3, 4, 5, 6, 7)
From the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With