https://kotlinlang.org logo
Title
k

Karlo Lozovina

10/19/2021, 8:59 PM
Given an expression
someCollection.take(42).forEach { /* ... */ }
is there a way to access the collection inside the forEach that the forEach is iterating over?
d

Damian Zawadzki

10/19/2021, 9:04 PM
someCollection
.take(42)
.let{ collection ->
    collection.forEach { item->
       // access to collection and item
     }
}
maybe something like this?
k

Karlo Lozovina

10/19/2021, 9:14 PM
that could work in some cases, but it's a bit verbose 😕 was hoping for some kind of implicit variable inside the forEach block, like
it
...
d

Damian Zawadzki

10/19/2021, 9:22 PM
you coiuld hide it behind extension
someCollection
                .take(42)
                .collectionForEach { collection, item ->
                    // access to collection and item
                }

//its modified original forEach extension
public inline fun <T> Iterable<T>.collectionForEach(action: (Iterable<T>, T) -> Unit): Unit {
    for (element in this) action(this, element)
}
But the question is, do you realy need it ? 🙂
👍 1
m

Marcus Brito

10/19/2021, 9:30 PM
well
someCollection
will be in scope anyway
so someCollection.take(42).forEach { item -> // someCollection is available here }
j

Joffrey

10/19/2021, 9:31 PM
@Marcus Brito yes, but I think the point was to use the collection of size <= 42 returned by
take(42)
, not the original one
m

Marcus Brito

10/19/2021, 9:31 PM
oh right, my bad
I’m curious why you would need to access the collection there, though. What are you trying to do?
4
k

Karlo Lozovina

10/19/2021, 10:18 PM
@Marcus Brito it's kind of hard to put into words: I'm dealing with lots of nested iterations over "views" of a single collection. For example, I could be like 5 iteration levels deep and would like the 6th level of iteration to start somewhere relative to the current one, and the current one relative to the previous one, etc... Right now I'm doing it "manually", with passing indexes everywhere and it's allright...
d

Damian Zawadzki

10/19/2021, 10:29 PM
sound more like recursive function, maybe you should try to rethink the problem not the solution. 6 nested loops sounds like overkill
☝️ 2