How to convert Java assignment expression to Kotlin

As @AndroidEx correctly stated, assignments are not expressions in Kotlin, unlike Java. The reason is that expressions with side effects are generally discouraged. See this discussion on a similar topic.

One solution is just to split the expression and move the assignment out of condition block:

a = b
if (a != c) { ... }

Another one is to use functions from stdlib like let, which executes the lambda with the receiver as parameter and returns the lambda result. apply and run have similar semantics.

if (b.let { a = it; it != c }) { ... }

if (run { a = b; b != c }) { ... }

Thanks to inlining, this will be as efficient as plain code taken from the lambda.


Your example with InputStream would look like

while (input.read(bytes).let { tmp = it; it != -1 }) { ... }

Also, consider readBytes function for reading a ByteArray from an InputStream.


Java: (a = b) != c

Kotlin: b.also { a = it } != c


Unlike the accepted answer, I recommend using Kotlin's also function, instead of let:

while (input.read(bytes).also { tmp = it } != -1) { ...

Because T.also returns T (it) itself and then you can compare it with -1. This is more similar to Java's assignment as an expression.


See "Return this vs. other type" section on this useful blog for details.

Tags:

Java

Kotlin