while表达式中不允许分配? [英] Assignment not allowed in while expression?

查看:70
本文介绍了while表达式中不允许分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们通常可以在while条件内执行赋值.但是科特林对此有所抱怨.因此以下代码无法编译:

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 .... \n")
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)
    }
}

这篇关于while表达式中不允许分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆