Home > OS >  Chaincall for each element in list
Chaincall for each element in list

Time:07-06

Is exist elegant way to call function on every element in list to tie with next till the end?

For example I have:

val list = listOf(1,5,3,4)
fun Int.foo(next: Int) = //some logic

I want to generate this expression:

val result = 1.foo(5).foo(3).foo(4)

CodePudding user response:

Such operation is called reducing or folding a collection and is done using reduce():

list.reduce(Int::foo)

For example:

1.plus(5).plus(3).plus(4) // 13
listOf(1, 5, 3, 4).reduce(Int::plus) // 13
  • Related