Igorock
Igorock

Reputation: 2891

Convert tuple of unknown length to List in 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?

Upvotes: 5

Views: 1009

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

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.

Upvotes: 10

Aditya Chopra
Aditya Chopra

Reputation: 80

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.

Upvotes: 1

Related Questions