kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

for vs forEach

Open mikehearn opened this issue 8 years ago • 6 comments

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.

mikehearn avatar Jan 05 '17 15:01 mikehearn

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.

cypressious avatar Jan 05 '17 15:01 cypressious

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

voddan avatar Jan 05 '17 15:01 voddan

Good point. Function references obviously lend themselves very well to being used with forEach.

cypressious avatar Jan 05 '17 15:01 cypressious

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.

mikehearn avatar Jan 05 '17 17:01 mikehearn

I think Item 46 and also Item 45 from Effective Java (3rd Edition) may be relevant to this discussion.

mahozad avatar Oct 03 '21 15:10 mahozad

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.

cable729 avatar Feb 03 '23 01:02 cable729