I'd probably create a set of utility functions like
def fromTuple2[A, That](t: Tuple2[A,A])(implicit bf : CanBuildFrom[Nothing, A, That]): That =
(bf.apply() += (t._1, t._2)).result();
for all the n-tuples you need. While it's a lot of boiler-plate code, it's just one-time job. And then you can do things like:
val e1: Either[String,Int] = Right(3);
val e2: Either[String,String] = Left("3");
val test: List[Either[String,Any]] = fromTuple2(e1, e2);
Perhaps better, we can use enrichment implicit methods such as
implicit def fromTuple2Impl[A](t: Tuple2[A,A]) = new {
def asCollection[That](implicit bf : CanBuildFrom[Nothing, A, That]): That =
(bf.apply() += (t._1, t._2)).result();
}
to write just
val test: List[Either[String,Any]] = (e1, e2).asCollection;
Edit: We can even enrich tuples to be Traversable
s, which gets us all methods like toList
, folding etc.:
implicit def fromTuple2Impl3[A](t: Tuple2[A,A]) = new Traversable[A] {
def asCollection[That](implicit bf : CanBuildFrom[Nothing, A, That]): That =
(bf.apply() += (t._1, t._2)).result();
override def foreach[U](f: (A) => U): Unit = {
f(t._1); f(t._2);
}
}
With some more work, we could take it further to implement IndexedSeq
.