如何在一行中输入五个以上的值?

How can I enter more than five values on one line?

我需要在 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> must have a 'component6()' function

在此先感谢您的帮助)

Kotlin 仅在 List 上定义了 component1()component5(),它用于解构,因此限制了您可以使用它做的事情。

不过,感谢Extension Functions,我们可以定义自己的:

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]

(等等...)

然后这应该可以工作:

val (x, y, z, f, e, m, s, t, c) = readInts() 

请注意,如果您的组件为空,这可能会像写的那样失败。