0

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)
1
  • Which part are you asking about? Have you tried changing it so you aren't trying to use the return of an assignment? Commented Jul 15, 2018 at 16:03

2 Answers 2

2

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()
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Using this I no longer get an error from my IDE but there seems to be an error with this code still, meaning that the result of this function is not the same as before. It is used to read Json from a URL, here I'm expecting a Json Array from the text being read but it is no longer the case...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.