Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

kotlin

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) {
}
like image 679
Jire Avatar asked Sep 15 '15 21:09

Jire


1 Answers

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
    ...
}
like image 79
Karol S Avatar answered Sep 29 '22 12:09

Karol S