Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tuple of unknown length to List in Scala

Tags:

scala

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?

like image 688
Igorock Avatar asked Dec 24 '22 09:12

Igorock


2 Answers

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 Strings to it. You might want to call _.toString instead.

like image 178
Andrey Tyukin Avatar answered Jan 09 '23 11:01

Andrey Tyukin


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.

like image 43
Aditya Chopra Avatar answered Jan 09 '23 10:01

Aditya Chopra