简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM