kotlin-style-guide
kotlin-style-guide copied to clipboard
for vs forEach
For loops vs forEach - two very similar constructs with very similar syntaxes:
for (foo in foos) { foo.thing() }
vs
foos.forEach { it.thing() }
I prefer the traditional for form, seeing as that's what forEach becomes anyway and it encourages you to pick a more meaningful iterator name than it, but I'm happy with either.
Suggested rule: use forEach only as the terminal operation of a chain of functional operations (map, filter, groupBy, etc). Don't use a variable name followed by .forEach { } instead of a for loop.
Use collection?.forEach {} if the collection is nullable.
Prefer for over forEach if you need to use break. As continue can be emulated by return@forEach, using it in either is fine.
I personally like using forEach if the operation I need to perform is short, like printing the element:
names.forEach {println(it)}
//or
names.forEach(::println)
I don't see a problem with forEach unless people try to do break or continue and invent "cleaver" workarounds
Good point. Function references obviously lend themselves very well to being used with forEach.
The function is more flexible, for sure. I'd also be OK with just standardising on "use forEach everywhere". It's more the consistency issue that's a pain.
I think Item 46 and also Item 45 from Effective Java (3rd Edition) may be relevant to this discussion.
Based on the readme, guidance on for vs forEach should not have been moved to the official coding conventions reference:
Issues where a sufficient amount of consensus has been reached are closed, and the rules are moved to the official style guide at https://kotlinlang.org/docs/reference/coding-conventions.html.
I recommend removing it from the coding conventions until a consensus has been reached.