3 ms·
Ah yes, it is a problem if a language is not clear about the lifetime semantics of a loop variable. In Ruby, for example, an idiomatic loop like 10.times{|i| .
by extension 17y ago
Ah yes, it is a problem if a language is not clear about the lifetime semantics of a loop variable.
In Ruby, for example, an idiomatic loop like 10.times{|i| ... } does indeed bind a new variable for every iteration, but that is implicitly clear to anyone with a basic understanding of the language. Likewise, the 3-part for loop of Java et al does not hide the fact that it's the same variable every time through the loop.
The Java for-each loop, on the other hand, is more ambiguous. A quick check seems to indicate that the iterator variable can be declared final and captured in an anonymous inner class. That means that for-each acts differently than for loop and I could see that confusing your average code monkey.
- _delirium 17y agoYeah, I think the main thing that's confusing about the particular example given in this thread is that the common case of looping over integers usually intends a foreach-style loop, but Java syntax doesn't make it easy to do something like for(final int i : Range(1,10)). So people end up using the C-style 3-part for loop when they don't have any real need for its power.
- ericlavigne 17y agoI actually think that will change in Java 7. I will likely not be using "for" very often, and will start using higher-order functions like map and fold. The issue is mainly developers for whom closures are a new concept. If they are too confused as they make their first nervous steps into the world of functional programming, if their first attempts at using closures result in a lot of bugs, then they may write off the whole thing as more complicated than it's worth.