Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring declaration initializer of type List<String> must have a 'component6()' function

Tags:

android

kotlin

Consider this method that converts a list of strings into some object:

/**
 * Creates an Item from the provided list of strings
 */
private fun createFromStrings(strings: List<String>): Item {
    val (str1, str2, str3, str4, str5) = strings

    // some string manipulation
    return Item(someString)
}

Adding a 6th variable to the destructuring declaration produces the following error:

Destructuring declaration initializer of type List must have a 'component6()' function

I can deduce from this that List can be destructured into up to 5 variables out of the box (out of convenience, perhaps).

Is there any relevant documentation on this? Are there some hints in Collections.kt that make this obvious? Or is it simply a case of.. see what works, accept it and just move on with your life?


1 Answers

As @gpunto correctly said, List doesn't come with a component6() method out of the box, so by default you can destructure up to 5 elements. However, if you really need/want to have a sixth (or seventh, or n-th) component you can always write your own extension:

operator fun <T> List<T>.component6(): T = get(5)

fun main() {
    val aList = listOf("one", "two", "three", "four", "five", "six")
    val (_, _, _, _, _, s6) = aList // no compilation error
    println(s6) // prints "six"
}
like image 104
user2340612 Avatar answered May 17 '26 03:05

user2340612