https://kotlinlang.org logo
j

janvladimirmostert

01/08/2021, 3:53 PM
Out of curiosity, is this output always guaranteed across Kotlin JVM, Android, JS, Native, etc? I'm assuming Kotlin breaks up those ++i and i++ into separate lines?
Copy code
var i = 0
val map = mutableMapOf<String, Int>()
(1..10).forEach {
   map["${++i}"] = ++i + i++
}
println(map)
{1=4, 4=10, 7=16, 10=22, 13=28, 16=34, 19=40, 22=46, 25=52, 28=58} To ask it differently, is the IR being generated always such that map[...] evaluates first, then the ++i and then the i++ ?
v

Vampire

01/08/2021, 3:58 PM
I hope so. The language should define the semantics, not the underlying system it is compiled to. If the result is not reliably identical, I'd call that a bug.
n

Nir

01/08/2021, 4:00 PM
Although, allowing such code to pass review is also a bug 🙂
In C++ where undefined behavior is more common (to allow for optimizations), answering a question like the above requires a PhD
j

janvladimirmostert

01/08/2021, 4:07 PM
yes, it's horrible code and if that was C++, the answer would probably depend on which compiler and which flags you're using I'm curious if Kotlin does something with such code so that it executes predictably on all platforms it compiles to
n

Nir

01/08/2021, 4:08 PM
I'm actually shocked that kotlin supports both ++i and i++
v

Vampire

01/08/2021, 4:08 PM
Why? sometimes you need either, sometimes the other
n

Nir

01/08/2021, 4:09 PM
post increment is just kind of confusing a source of bugs, in C and C++.
Even in C++ where you have to use incrementing far more, it's almost always clearer to just do the increment on its own line
v

Vampire

01/08/2021, 4:10 PM
Every language construct can be confusing and source of bugs if you don't understand and use it properly 😄
😂 1
n

Nir

01/08/2021, 4:10 PM
In Kotlin I actually would have just made ++ a statement, not an expression. This is consistent with the fact that a += 1 is not an expression (unlike C++)
Sure, but some are more prone than others. A decade of C++ later, I still see people make mistakes with these (sometimes when they are explaining how intuitive they are)
It's also less likely to be clear to the average kotlin dev because it's used far far less, so the rare times it is used, better to be more verbose and clear. In C and C++, you use ++ far more often (for a few reasons)
a

Animesh Sahu

01/09/2021, 6:51 AM
I'm actually shocked that kotlin supports both ++i and i++
Kotlin even has unary operator (like +i -i) 😛
4 Views