4 ms·
Saw this pop up in my IDE this morning, excited to upgrade. The auto-for-loop-refactoring is interesting. I've found I never use for-loops in Kotlin - between
by nostrademons 10y ago
Saw this pop up in my IDE this morning, excited to upgrade. The auto-for-loop-refactoring is interesting. I've found I never use for-loops in Kotlin - between the abundance of iterator methods and concise trailing-closure syntax, it always ends up being more concisely expressed as collection.forEach { ...body... }. Seems like the language may be going that way too; I wonder if we'll eventually see the for-loop start to fall out of use in modern languages.
- djfm 10y agoI make it a point never to use a for loop in JS. It's sometimes tricky but often leads to cleaner code.
- mike_hearn 10y agoWhat's unclean about for loops?
- tlarkworthy 10y agoMutating index state variables, and it's not functional (you can't pass a function to be the inner loop)
- deleted 10y ago[deleted]
- willtim 10y agoFor loops require explicit and error-prone use of integer indices and are of limited utility outside arrays. Foreach loops in Java/C# are an attempt to generalise, but they are really just syntactic sugar over external iterators. They give privileged status to the specific iteration interface chosen, entangling the language and its libraries. The actual Iterator interface chosen by Java has proven to be unsuitable for coroutines/yield, but is now too difficult to change. In Haskell, foreach loops can be implemented purely as a higher-order library function.
- mike_hearn 10y agoYeah, I was meaning 'for loops' to include the modern sense of foreach loops too. Java doesn't distinguish and Kotlin doesn't have the old style at all. There's no rule that says a for loop must only support a single iteration interface. That seems more like an implementation detail of the compiler than a problem with for loops in general.
- willtim 10y agoOf course the big elephant in the room that I didn't mention, is that for loops get work done via mutation. This is perhaps what was mean't by “unclean".
- sdegutis 10y agoBut does .forEach compile to an efficient for-loop in Kotlin?
- nostrademons 10y agoNot completely sure about the internals of the Kotlin compiler, but I believe it does. You can do a non-local return (i.e. return from the top-level function, not the lambda passed to .forEach) from inside them. This would be very difficult if the body were not inlined, because you'd need to store a lexical stack of return addresses and ensure that the closure never escapes the HOF. (I think it actually does perform this escape analysis; I've gotten error messages before when trying to pass a lambda with a non-local return into a functional argument that wasn't one of the basic collection iterators.)
- deleted 10y ago[deleted]