Home > OS >  Kotlin foreach return list
Kotlin foreach return list

Time:06-11

simple question, is there a method for a collection to apply action on every element (like foreach) but who return the list

I can write it myself :

public inline fun <T> Iterable<T>.myforEach(action: (T) -> Unit): Iterable<T> {
   for (element in this) action(element)
        
   return this
}

But it must already exist

CodePudding user response:

There is onEach for this:

val sameList = list.onEach { doStuff() }
  • Related