Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin destructuring more than five components

Tags:

kotlin

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?

like image 606
Gavin Avatar asked Apr 28 '19 13:04

Gavin


Video Answer


1 Answers

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.

like image 131
Willi Mentzel Avatar answered Sep 19 '22 11:09

Willi Mentzel