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


#1

Hi!

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?


#2

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 https://youtrack.jetbrains.com/issues/KT?


#3

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.


#4

I’ll do that, thanks!

https://youtrack.jetbrains.com/issue/KT-22068


#5

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