Flatten a list of tuples in Scala?
If the implicit conversion can't be found you can supply it explicitly.
pq.flatten {case (a,b) => List(a,b)}
If this is done multiple times throughout the code then you can save some boilerplate by making it implicit.
scala> import scala.language.implicitConversions
import scala.language.implicitConversions
scala> implicit def flatTup[T](t:(T,T)): List[T]= t match {case (a,b)=>List(a,b)}
flatTup: [T](t: (T, T))List[T]
scala> pq.flatten
res179: List[Char] = List(a, p, b, q, c, r, d, s, e, t)
jwvh's answer covers the "coding" solution to your problem perfectly well, so I am not going to go into any more detail about that. The only thing I wanted to add was clarifying why the solution that both you and jwvh found is needed.
As stated in the Scala library, Tuple2
(which (,)
translates to) is:
A tuple of 2 elements; the canonical representation of a
Product2
.
And following up on that:
Product2
is a cartesian product of 2 components.
...which means that Tuple2[T1,T2]
represents:
The set of all possible pairs of elements whose components are members of two sets (all elements in
T1
andT2
respectively).
A List[T]
, on the other hand, represents an ordered collections of T
elements.
What all this means practically is that there is no absolute way to translate any possible Tuple2[T1,T2]
to a List[T]
, simply because T1
and T2
could be different. For example, take the following tuple:
val tuple = ("hi", 5)
How could such tuple be flattened? Should the 5
be made a String
? Or maybe just flatten to a List[Any]
? While both of these solutions could be used, they are working around the type system, so they are not encoded in the Tuple
API by design.
All this comes down to the fact that there is no default implicit view for this case and you have to supply one yourself, as both jwvh and you already figured out.