使用readLine()方法拆分Kotlin字符串

Kev*_*ick 1 java kotlin

所以我有这个Java代码:

String values = input.nextLine();
String[] longs = values.split(" ");
Run Code Online (Sandbox Code Playgroud)

将字符串输入拆分为字符串数组.

我在Kotlin尝试

var input: String? = readLine()
var ints: List<String>? = input.split(" ".toRegex())
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:"在String类型的可空接收器上只允许安全(?.)或非空断言(!!.)调用?"

我是Kotlin的新手,想要明白如何做到这一点.谢谢!

s1m*_*nw1 8

如果你看一下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()
Run Code Online (Sandbox Code Playgroud)

因此,调用split其结果是不安全的,您必须处理该null案例,例如如下:

val input: String? = readLine()
val ints: List<String>? = input?.split(" ".toRegex())
Run Code Online (Sandbox Code Playgroud)

其他替代方案和更多信息可在此处找到.

  • 我认为这应该是公认的答案 (4认同)