Kotlin 如何在一行中输入五个以上的值?
我需要在Kotlin的一行中输入九个值:Kotlin 如何在一行中输入五个以上的值?,kotlin,destructuring,Kotlin,Destructuring,我需要在Kotlin的一行中输入九个值: fun readInts() = readLine()!!.split(' ').map { it.toInt() } fun main(){ val (x, y, z, f, e, m, s, t, c) = readInts() 但当我尝试这样做时,我得到了一个错误: Error:(5, 30) Kotlin: Destructuring declaration initializer of type List<Int> m
fun readInts() = readLine()!!.split(' ').map { it.toInt() }
fun main(){
val (x, y, z, f, e, m, s, t, c) = readInts()
但当我尝试这样做时,我得到了一个错误:
Error:(5, 30) Kotlin: Destructuring declaration initializer of type List<Int> must have a 'component6()' function
错误:(5,30)Kotlin:List类型的Destructuring声明初始值设定项必须具有“component6()”函数
提前感谢您的帮助)Kotlin仅通过
列表上的component5()
定义了component1()
,它用于分解结构,因此限制了您对它的使用
但是,多亏了,我们可以定义自己的:
operator fun <T> List<T>.component6(): T = this[5]
operator fun <T> List<T>.component7(): T = this[6]
operator fun <T> List<T>.component8(): T = this[7]
operator fun <T> List<T>.component9(): T = this[8]
请注意,如果您的组件为空,则编写时可能会失败。Kotlin仅通过列表上的component5()
定义了component1()
,它用于分解结构,因此限制了您可以对其执行的操作
但是,多亏了,我们可以定义自己的:
operator fun <T> List<T>.component6(): T = this[5]
operator fun <T> List<T>.component7(): T = this[6]
operator fun <T> List<T>.component8(): T = this[7]
operator fun <T> List<T>.component9(): T = this[8]
请注意,如果您的组件为空,这可能会失败。这是一个列表,而不是9元素元组。它需要在一行上的任何特殊原因?它是一个列表,而不是9元素元组。它需要在一行上的任何特殊原因?