Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over arbitrary-length tuple

I just started with Scala and ran into a problem:

Scala has the Types Tuple1, Tuple2, …, Tuple22. Scalaquery returns tuples when iterating over queries.

I have now a given class (ZK’s ListitemRenderer), which accepts Objects and populates gui lists with rows, each consisting of some cells. But ListitemRenderer isn’t generic. So my problem is that i have an Object “data”, which really is a tuple of arbitrary length, which i have to iterate over to create the cells (simply with data._1.toString, …).

Since there is no I didn’t know the supertype to Tuple1-22, i can’t couldn’t just do data.asInstanceOf[Tuple].productIterator foreach {…}

What can i do?


Below Answer told me that there is indeed a Trait to all Tuples – Product – providing the desired foreach function.

like image 899
flying sheep Avatar asked May 24 '11 20:05

flying sheep


People also ask

Can you iterate over a tuple?

We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.

How do you iterate through a tuple list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by refering to their indexes. Remember to increase the index by 1 after each iteration.

How do you create a tuple for a loop in Python?

Method 1: Using For loop with append() method Here we will use the for loop along with the append() method. We will iterate through elements of the list and will add a tuple to the resulting list using the append() method.


1 Answers

All TupleX classes inherit from Product, which defines def productIterator : Iterator[Any]. You can call it to iterates through all elements of any tuple.

For example:

def toStringSeq(tuple: Product) = tuple.productIterator.map(_.toString).toIndexedSeq
like image 133
Jean-Philippe Pellet Avatar answered Sep 25 '22 01:09

Jean-Philippe Pellet