Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


The 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.


> 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"));




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: