Given an expression `someCollection.take(42).forEa...
# getting-started
k
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
Copy code
someCollection
.take(42)
.let{ collection ->
    collection.forEach { item->
       // access to collection and item
     }
}
maybe something like this?
k
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
you coiuld hide it behind extension
Copy code
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
well
someCollection
will be in scope anyway
so someCollection.take(42).forEach { item -> // someCollection is available here }
j
@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
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
@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
sound more like recursive function, maybe you should try to rethink the problem not the solution. 6 nested loops sounds like overkill
☝️ 2