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 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].produc开发者_JAVA百科tIterator foreach {…}
What can i do?
Below Answer told me that there is indeed a Trait to all Tuples – Product
– providing the desired foreach
function.
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
精彩评论