Force usage of "it" in .forEach{} calls



I recently found a nasty bug that was really hard to spot. What happened was that the code had a list with a .forEach{} call like this:

introAnimationViews.forEach { visibility = View.INVISIBLE }

when it was supposed to do:

introAnimationViews.forEach { it.visibility = View.INVISIBLE }

We wasted too much time on such a simple bug :slight_smile: I would like to propose there should be a compile error for this when “it” is not used in a .forEach{} since it doesn’t make any sense to iterate on a list without actually doing anything with its content.

I also checked with a colleague Swift developer and it seems Swift is giving a compile error for this scenario which I think is a proper safe guard for developers.

Sounds like a good idea?


I think this is a valid request for an IDE inspection rather than a compiler error. Could you file a feature request for that to


There are also various cases where I don’t actually use the parameter value. For example in an Android onClick handler that handles a single view/button it is not needed to use the view parameter.


I’ll do that, thanks!


A post was split to a new topic: forEach with elements as the receivers