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

查看:40
本文介绍了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)
    }
}

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

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