Kotlin Tip #42: Use fold
and reduce
for Aggregating Collection Values — 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #41: Make use of the first, last, and find methods for retrieving elements
At first look, “fold” and “reduce” might look the same because both are ways to combine values in a collection. But, the difference is in how they start and what kinds of results they give.
Reduce
works by starting with the first item of the collection to build up a result, then it applies the action using the second item and keeps going from there. This means that reduce
needs at least one item in the collection to work, and it can only produce a result that is the same type as the items in the collection.
fold
, on the other hand, introduces the idea of a starting value. This starting value is the beginning for adding up, and it lets the result be different from the type of items in the collection.
Choosing between “fold” and “reduce” depends on two things: if there is a starting value and if you want the result to be flexible in its type.
Use “reduce” when you’re sure the collection has items and the result is the same type as the items. Choose “fold” when you need a starting value, either for logical reasons or to make sure the types match.
Consider a scenario where we need to add up the lengths of strings in a collection. With “fold,” we can do this smoothly, even if the collection is empty, by starting from an initial number.
This example shows how flexible “fold” is. It highlights its usefulness when the starting point of adding up is important or when we might have collections with no items.
By knowing how to use these functions right, developers can make their Kotlin code shorter, easier to read, and more efficient. Whether it’s adding numbers, joining strings, or combining custom data types, “fold” and “reduce” help developers put together complex ideas in a clear and typical Kotlin way.
I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Tip #43: Coming soon!
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.