Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

kotlin

In Kotlin, if you want to use the element of the forEach, you can use the it keyword. So now I wonder that what should I do if I have a forEach inside forEach like that:

list.forEach {     val parent = it     it.forEach {         // `it` now become the element of the parent.     } } 

I think that defines a new variable only for the naming convention be so stupid. Have any other solution for this problem?

like image 540
Trần Đức Tâm Avatar asked Jul 20 '17 02:07

Trần Đức Tâm


People also ask

Can you nest foreach loops?

The nesting operator: %:% I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects. It also returns a foreach object, which is essentially a special merger of its operands.

Can you foreach inside foreach?

You're welcome. You only need one foreach , and break; stops the loop.

Can you have a for loop inside a for loop?

Note: It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.

What is the use of foreach loop?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.


2 Answers

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

collection.forEach { customName ->      ... } 
like image 165
dniHze Avatar answered Oct 07 '22 01:10

dniHze


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.

like image 25
Patrick Steiger Avatar answered Oct 06 '22 23:10

Patrick Steiger