Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Chaincall for each element in list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading