Nested forEach, How to distinguish between inner and outer loop parameters?

it is just a default param name inside of all single argument closures. You could specify param name by yourself:

collection.forEach { customName -> 
    ...
}

In addition to the correct answer above by Artyom, I'd like to say that if you only care for the inner it, you can simply ignore the name overloading.

See:

>>  var a = "abc"
>>  a?.let { it[2]?.let { it } }
c

The value returned is the most inner "it". "it", there, refers to the outermost "it[2]", that is, the character 'c' from the string "abc".

Now, if you want to access the outermost "it", you should name it something else like Artyom says. The code below is equivalent to the code above, but it allows you to refer to "outerIt" from the outer 'let' block in the innermost 'let' block, if that's what you need.

>>  var a = "abc"
>>  a?.let { outerIt -> outerIt[2]?.let { it } }
c

This way, if you need to refer to the outermost it, you can. For example:

>>  var a = "abc"
>>  a?.let { outerIt -> outerIt[2]?.let { "${outerIt[1]} $it" } }
b c

If you don't need to refer to the outermost "it", I'd personally prefer the first construct because it is terser.

Tags:

Foreach

Kotlin