How to flatten nested tuples in scala

Table of contents
Reading Time: 2 minutes

In a project which I’ve been working on, I encountered a situation to flatten a nested tuple but couldn’t come up with a way to do so, hence out of curiosity I started googling about it and came to the following conclusion.

As for an example I had a structure something similar to the one mentioned below, though not identical:

and, supposedly I wanted to make structureToOperateOn something like this:

So the first thing that came to my mind was to use foldLeft:

which resulted in something like this:

Next, I thought of flattening the tuples and came across Shapeless. Although I think scala should have something to flatten tuples, the best way it could be done as of now is to use Shapeless library. Anyways, this is how flattening tuples using Shapeless works:

After messing around with nested tuples, I finally thought it’d be better to have an alternative way to get the required result instead of adding a new library in the project. Regardless, it could be very helpful in scenarios where you might get stuck and would want to ultimately flatten a tuple.

This was what I used as an alternative:

which resulted in:

So to conclude, you can use Shapeless in order to flatten complex nested tuples if need be.

 

 

Written by 

Sidharth is a Lead Consultant, having experience of more than 4.5 years. He has started working on Scala and Clojure and is actively involved in other developmental work. He enjoys working in a team and believes that knowledge is something that should be shared openly and on a large scale. As an avid gamer and passionate player, he likes to be involved in both indoor and outdoor activities.

5 thoughts on “How to flatten nested tuples in scala2 min read

  1. I don’t think that is the standard meaning of flatten. My recollection is that flattening your original list should produce: (a1, a2, a3, b1, b2, b3, c1, c2, c3, 10, 1, 11).

    1. Hi Scott, in the example I wanted to flatten (((“a1″,”b1″),”c1”),10), (((“a2″,”b2″),”c2”),1) and (((“a3″,”b3″),”c3”),11) individually after using foldLeft so as to get something like:
      “a1”, “b1”, “c1”, 10
      “a2”, “b2”, “c2”, 1
      “a3”, “b3”, “c3”, 11
      I modified the flattening example a bit so as to make things more clear.

Comments are closed.

Discover more from Knoldus Blogs

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

Continue reading