Aelian
Aelian

Reputation: 23

"Assignments are not expressions error" after converting Java to Kotlin

I converted some Java classes to kotlin and an "Assignments are not expressions, and only expressions are allowed in this context" error pops up when I try to run this code which worked fine in Java:

@Throws(IOException::class)
private fun readAll(rd: Reader): String {
    val sb = StringBuilder()
    var cp: Int
    while ((cp = rd.read()) != -1) {
        sb.append(cp.toChar())
    }

    return sb.toString()
}

The line causing the problem:

while ((cp = rd.read()) != -1)

Upvotes: 0

Views: 646

Answers (2)

user8959091
user8959091

Reputation:

Exactly as the message says in Kotlin you can't use the assignment as an expression. You can do this:

private fun readAll(rd: Reader): String {
    val sb = StringBuilder()
    var cp: Int
    do {
        cp = rd.read()
        if (cp == -1)
            break
        sb.append(cp.toChar())      
    } while (true) // your choice here to stop the loop 
    return sb.toString()
}

Upvotes: 2

Peter Samokhin
Peter Samokhin

Reputation: 874

In Kotlin you can't do this:

while ((cp = rd.read()) != -1)

You should use something like this:

var cp = rd.read()
while (cp != -1) {
    // your logic here
    cp = rd.read()
}

Or something like this:

while (true) {
    val cp = rd.read()
    if (cp < 0) break

    // your logic here
}

Because assignment (cp = rd.read()) is expression in Java, but not in Kotlin.

Upvotes: 0

Related Questions