

forEach.Īdditionally, your constructor parameters to the data class are normal parameters, and as such, need commas between them!

Justifying it with code that resembles “perl poetry” or “obfuscated C” compared to the elegance of a C for loop is trying to put lipstick on a pig. Why not admit that elimination of some language features in Kotlin, even when necessitated by other concerns, is a regression not evolution, which we live with to enjoy real improvements it offers. The examples of Kotlin code you provide speak volumes to your ability to handle complexity and grasp non-intuitive constructs. Please, don’t tell me that you are confused by C-for loop’s complex syntax or difficulty of intuiting its operation. The while loop does create equivalent code but the beauty of C-for syntax was to eliminate such ugly boiler plate in the first place.

Only to be followed by “new improved” language constructs that go into a long discussion of Iterable vs Sequence vs range operations, to wind up with a lot more code and hidden implications that must be considered (instantiation of the full list being one, foreach being about 3x slower than explicit for loop is another). When I read threads like this I feel like I fell into a Bizzaro Universe where the simplicity of a C for loop with its explicitly exposed initialization, looping condition and next iteration stepping, without any hidden costs that you have to “keep in mind” beyond what you write, is considered undesirable. There could be additional motivation, but in general I think that classic for loop should be deprecated and replaced by functional-style operations wherever it is possible. In my example, you can simply replace i by AtomicInteger and make your operations thread safe. Pitfall number four occurs when you have some parallel operations messing with i. In my example you can do it easily by replacing if by when.

You will have to either delegate step calculation to additional function which is even worse, or rewrite everything. You won’t be able to do it with for anymore. Pitfall number three: Suppose you want a more complicated behavior and need three different steps instead of two. You do it in one place, but forget to do in another and now you have two iterations with different number of steps. Pitfall number two: For some reason, you want to change the behavior of your dynamic step. You should obviously never do it, but changing the increment is the first step in this direction. Pitfall number one: You accidentally or intentionally changing i somewhere inside your loop. The problem arises when you have a large code.
