while 表达式中不允许赋值?

while 表达式中不允许赋值?

问题描述:

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

In Java we can usually perform an assignment within the while condition. However Kotlin complains about it. So the following code does not compile:

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

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

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

According to this other thread, this seems the best solution:

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);
}

是吗?

不,IMO,最好的方法是

No, the best way, IMO, would be

val reader = BufferedReader(reader)
reader.lineSequence().forEach {
    println(it)
}

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

And if you want to make sure the reader is properly closed (as you would with a try-with-resources statement in Java), you can use

BufferedReader(reader).use { r ->
    r.lineSequence().forEach {
        println(it)
    }
}