表达时不允许分配?

Ped*_*roD 17 kotlin kotlin-interop

在Java中,我们通常可以在while条件内执行赋值.然而Kotlin抱怨它.所以下面的代码不能编译:

val br = BufferedReader(InputStreamReader(
        conn.inputStream))

var output: String
println("Output from Server .... \n")
while ((output = br.readLine()) != null) { // <--- error here: Assignments are not expressions, and only expressions are allowed in this context
    println(output)
}
Run Code Online (Sandbox Code Playgroud)

根据这个其他线程,这似乎是最好的解决方案:

val reader = BufferedReader(reader)
var line: String? = null;
while ({ line = reader.readLine(); line }() != null) { // <--- The IDE asks me to replace this line for while(true), what the...?
  System.out.println(line);
}
Run Code Online (Sandbox Code Playgroud)

但是吗?

JB *_*zet 30

不,最好的方式,IMO,将

val reader = BufferedReader(reader)
reader.lineSequence().forEach {
    println(it)
}
Run Code Online (Sandbox Code Playgroud)

如果你想确保读者正确关闭(就像在Java中使用try-with-resources语句一样),你可以使用

BufferedReader(reader).use { r ->
    r.lineSequence().forEach {
        println(it)
    }
}
Run Code Online (Sandbox Code Playgroud)


Vad*_*zim 11

这里是Roman Elizarov的短Kotlin式通用解决方案:

while (true) {
    val line = reader.readLine() ?: break
    println(line);
}
Run Code Online (Sandbox Code Playgroud)

  • 最佳简短答案 (2认同)

Vad*_*zim 10

这是由stdlib 提供支持的最短解决方案,它也能安全地关闭阅读器:

reader.forEachLine {
    println(it)
}
Run Code Online (Sandbox Code Playgroud)