Coding Time: Folding Collections in Kotlin

Luka Giorgadze
Javarevisited
Published in
2 min readFeb 1, 2021
Photo by Maximilian Weisbecker on Unsplash

Recently, my teammate and I paired on a task that included matching values from different lists. In the process, I realized that I was not familiar with the Iterable<T>.fold() operation in Kotlin… well, rather my teammate realized that and teased me about it for a while.

Thus, the first thing I did the next morning was opening the Kotlin Koan for the fold operation!

Setup

There is a Shop that tracks the history of its Customers who have Order ‘s with certain Product ‘s:

The task is: for a given shop get the list of products that were ordered by every customer. And, of course, use the fold function.

Solving the problem with what I already know

My first step was to simply solve the problem — I needed to get the list of orders for each customer and find the intersections of these lists:

The initial mapping of a List <Customer> to List<List<Product>> felt unnecessary, so I removed it. Furthermore, I added a getter to Customer that returned all Product ‘s ordered by that Customer.:

Both of these passed the Koan test, so it was time to use the fold function.

Solving the problem with the fold function

This is how the function is defined:

Great, my initial the value would be the product ordered by the first customer and operation is the same intersect I’ve been using:

Looks very neat and concise! Let’s add a guard for a case when the customer list is empty:

Comparing with the solution

And, finally, the Kotlin academy’s own solution:

Hooray, I was actually quite close! My solution is even a little bit more concise as it does not have the first iteration overall customers to get a list of all purchased products.

I hope you have found this interesting!

How about giving it a try yourself?

--

--

Luka Giorgadze
Javarevisited

Developing software by day, sharing my experience by night (or vice versa)