Maybe a basic question, but I want to filter a lis...
# announcements
c
Maybe a basic question, but I want to filter a list, call a function with each matching element, then collate the results to a new list. Is there a more elegant way than this:
Copy code
val filtered = all.filter { it.foo }
   .map {
      callFunction(it)
      return it
   }.toList()
g
this looks as wrong snippet
return it
doesn’t work in lambda, it returns from enclosing function
Also
toList()
is useless in this case
and for side efects you can use
onEach
val filtered = all.filter { it.foo } .onEach { callFunction(it) }
c
onEach - that's what I was looking for!
thanks
g
But I would just split this:
Copy code
val filtered = all.filter { it.foo }
filtered.forEach { callFunction(it) }
because I don’t see for this particular snippet reason to combine these operations in a single chain if
callFunction
doesn’t modify
it
c
for readability?
g
also you can use method reference:
Copy code
onEach(::callFunction)
to be more explicit, if I have chain I usually expect that each operator somehow modifies it
👍 2
but in this case it’s just side effect
anyway forEach has good use cases, such as logging
so I wouldn’t say that splitting is always better, depends on use case and context
c
ok, thanks for all the info.
👍 1