用readLine()方法分割Kotlin字符串

所以我有这个Java代码:

String values = input.nextLine(); String[] longs = values.split(" "); 

它将字符串输入分割成一个字符串数组。

我在Kotlin尝试

 var input: String? = readLine() var ints: List? = input.split(" ".toRegex()) 

我得到一个错误:“在Stringtypes的可为空的接收器上只允许安全(?)或非null断言(!!)调用?

我是Kotlin的新手,想知道如何做到这一点。 谢谢!

如果你看一下readLine()就会发现它可能返回null

 /** * Reads a line of input from the standard input stream. * * @return the line read or `null` if the input stream is redirected to a file and the end of file has been reached. */ public fun readLine(): String? = stdin.readLine() 

因此,对结果调用split是不安全的,你必须处理null情况,例如:

 val input: String? = readLine() val ints: List? = input?.split(" ".toRegex()) 

其他的选择和进一步的信息可以在这里find。

你看,你的代码几乎是正确的,只是错过了!! 这确保字符串不应该是空的(它会引发错误)。 你的代码应该是这样的:

 val input: String? = readLine() var ints: List? = input!!.split(" ".toRegex()) 

请注意,我刚刚添加!! 运算符,并将第1行的var更改为val ,因为您的输入不应被更改(由用户提供)。