Assignment not allowed in while expression?

匆匆过客 提交于 2019-11-30 04:50:53
JB Nizet

No, the best way, IMO, would be

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

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

Here is the shortest solution powered by stdlib that also safely closes the reader:

reader.forEachLine {
    println(it)
}

And here is short Kotlin-style general solution by Roman Elizarov:

while (true) {
    val line = reader.readLine() ?: break
    println(line);
}

Here break has Nothing type that doesn't affect type inference for the line.

In cases you just want to replace while ((x = y.someFunction()) != null) you may use the following instead:

generateSequence { y.someFunction() }
          .forEach { x -> /* what you did in your while */ }

generateSequence will extract you all the values one by one until the first null is reached. You may replace the .forEach with a reduce or fold (or anything else that seems appropriate ;-)) if you want to keep the last value or sum up the values to something else.

For your specific use case however you may just use what JB Nizet in his answer has shown or use useLines:

reader.useLines {
  it.forEach(::println)
}

.forEachLine is probably the next best short-hand solution to that specific readLine-problem (already answered here) if you know you just want to read all lines and then stop.

(This Example for while loop ) Hope this example will help you..

Change from

while ((c = is.read(buffer)) > 0) { sb.append(String(buffer, 0, c, Charset.forName(UTF8))) }

to

while ({c = is.read(buffer);c}() > 0) { sb.append(String(buffer, 0, c, Charset.forName(UTF8))) }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!