Jire Jire - 1 year ago 68
Java Question

Why can't I do an assignment in a loop guard?

Why is this syntax not valid? The error IntelliJ reports is that only expressions are allowed in such context (line 2). I am wondering if there is some syntax to use to get around this, as Java allowed this type of assignment in loop feature.

var c: Int;
while ((c = reader.read()) != 1) {

Answer Source

The syntax is not valid, because c = reader.read() is not an expression in Kotlin – this prevents all the == vs = bugs.

You have to rewrite it as:

while (true) {
    val c = reader.read()
    if (c == 1) break
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download