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 Object
s 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With