Iterate over a tuple

I need to implement a general method that takes a tuple and returns a map Example:

val tuple=((1,2),(("A","B"),("C",3)),4) 

I am trying to break this tuple into a list:

 val list=tuple.productIterator.toList Scala>list: List[Any] = List((1,2), ((A,B),(C,3)), 4) 

But this method returns List [Any].

Now I'm trying to figure out how to iterate over the following tuple, for example:

 ((1,2),(("A","B"),("C",3)),4) 

to iterate over each element 1,2, "A", B ", ... etc. etc. How could I do such an iteration over a tuple

+7
source share
4 answers

And what?

 def flatProduct(t: Product): Iterator[Any] = t.productIterator.flatMap { case p: Product => flatProduct(p) case x => Iterator(x) } val tuple = ((1,2),(("A","B"),("C",3)),4) flatProduct(tuple).mkString(",") // 1,2,A,B,C,3,4 

Well, Any problem remains. At least this is due to the return type of productIterator .

+14
source
 tuple.productIterator map { case (a,b) => println(a,b) case (a) => println(a) } 
+2
source

Instead of tuples, use Shapeless data structures such as HList. You can have general processing and also not lose type information.

The only problem is that the documentation is not exhaustive.

+2
source

This works for me. tranform is a tuple consisting of dataframes

 def apply_function(a: DataFrame) = a.write.format("parquet").save("..." + a + ".parquet") transform.productIterator.map(_.asInstanceOf[DataFrame]).foreach(a => apply_function(a)) 
0
source

All Articles