4 ms·
Interestingly, Java has both styles. You can do for (var i : list) {...} or list.forEach(i -> ...); Except for cases with local variables, I have ab
by dehrmann 5y ago
Interestingly, Java has both styles. You can do
for (var i : list) {...}
or
list.forEach(i -> ...);
Except for cases with local variables, I have absolutely no idea which I should prefer. Kotlin makes a cute case for the functional style with it's lambda shorthand:
list.forEach {
...
}
I've found the functional style helpful for times I want almost add a language feature to avoid boilerplate. The functional style was added without special-purpose language changes, but the iterator version required Java to add Collections, Iterators, and eventually fancy for-each syntactic sugar.
- entropicdrifter 5y agoThe big advantage of the functional style in Java is that you are disallowed at the compiler level from modifying the contents of the collection you're iterating over. That sort of compiler-enforced good practice is definitely for the best.
- dehrmann 5y ago> you are disallowed at the compiler level from modifying the contents of the collection you're iterating over This fails at runtime, not compile time for me: x.forEach(i -> x.add("a"));