I need a method which will receive tuple of unknown length (Tuple2, Tuple3 or TupleX) and return list of tuple elements. I wrote the following method, but I get an error that it cannot cast type Any
to String
in the List:
def toList(tuple: Product): List[String] = tuple match {
case (s1, s2) => List(s1, s2)
case (s1, s2, s3) => List(s1, s2, s3)
}
Could you please help to fix above example or propose another solution?
All TupleN
type inherit from Product
, and Product
has the method productIterator
(documentation link), so you can write:
def toList(tuple: Product): List[String] =
tuple.productIterator.map(_.asInstanceOf[String]).toList
Note that this is not type safe. It will throw errors whenever your are passing anything that is not a tuple of String
s to it. You might want to call _.toString
instead.
You may try this if you are not sure that your input is string or something else:
def toList(tuple: Product): List[String] = {
tuple.productIterator.map(_.toString).toList
}
toList("1",2,3.0)
The above method works for String, Int, Double as you may see above.
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