10

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.

flying sheep
  • 8,475
  • 5
  • 56
  • 73

1 Answers1

17

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
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • so i do `data.asInstanceOf[Product].productIterator foreach {…}`? – flying sheep May 24 '11 at 22:15
  • @flying sheep: That should do the trick, but you could type the `data` argument of your function as a `Product` instead of `Any` or `AnyRef` (I guess you mean that when you say `Object`). That would save you the cast. – kassens May 24 '11 at 22:29
  • as said in the question: the function i’m in implements a function from a non-generic interface, so i can’t change the typing and have to cast, except scala has a way to monkeypatch the the interface to be generic. – flying sheep May 25 '11 at 09:27