Assignment not allowed in while expression?
Asked Answered
B

6

27

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

But is it?

Bivalent answered 8/1, 2017 at 20:40 Comment(0)
H
39

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)
    }
}
Heap answered 8/1, 2017 at 20:54 Comment(0)
P
25

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

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

Here break has Nothing type that also helps to promote type inference for the line as non-nullable string.

Pique answered 22/4, 2017 at 10:5 Comment(0)
P
13

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

reader.forEachLine {
    println(it)
}
Pique answered 22/4, 2017 at 9:46 Comment(0)
H
4

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.

Housekeeping answered 31/1, 2019 at 9:6 Comment(0)
G
2

I found that these days IntelliJ converts your Java code into the following kotlin code:

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

var output: String
while (br.readLine().also { output = it } != null) {
    println(output)
}

This is still confusing but it's quite readable. It uses the fact that also returns the receiver instance (the result of br.readLine() here).

Germany answered 22/4, 2021 at 4:44 Comment(0)
D
-1

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

Dependence answered 13/4, 2018 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.