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?
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"
}
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