Assignment not allow in while expression?

That only works if you are incrementing by 1.

++current

is the same as

{ current = current + 1; return current; }

In fact, ++i is a perfect example of an assignment as an expression and it is immensly useful.  ++i both assigns to i and as an expression it returns the value that was assigned to i.  Increment and decrement operators are just examples of situations where assignments as expressions are very useful, I would just like to see them extended to more than the trivial increment-by-one and decrement-by-one operations.

For the slightly more complex case consider:

i += 2


To take it a little further:

current = FetchNext(current)

where FetchNext is some operation that gets the next item in a series from a remote source.

Currently, in Kotlin these would have to be,

{ i += 2; return i}
{ current = FetchNext(current); return current }

respectively.

3 Likes