If you find yourself doing much of this kind of thing, the Shapeless library provides some really nice ways to work with tuples without giving up type safety.
For example, you could write the following using Shapeless's prepend operator for tuples (+:
) and the standard library's zipped
, which lets you avoid the creation of intermediate collections:
(seq1, seq2).zipped.map(_ +: _)
This is beautiful, type-safe, and for large collections it'll be more performant than solutions using zip
.
You could of course also use zipped
without Shapeless:
(seq1, seq2).zipped.map { case (a, (b, c)) => (a, b, c) }
Or:
(seq1, seq2).zipped.map((a, b) => (a, b._1, b._2))
In addition to the fact that this doesn't build an intermediate collection of tuples, the fact that map
here takes a function of two arguments (instead of a function from tuples) can sometimes make the syntax a little cleaner (as you can see in the +:
example above).