Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tuple to array in Scala

Tags:

scala

What is the best way to convert a tuple into an array in Scala? Here "best" means in as few lines of code as possible. I was shocked to search Google and StackOverflow only to find nothing on this topic, which seems like it should be trivial and common. Lists have a a toArray function; why don't tuples?

like image 605
ubadub Avatar asked Sep 09 '26 02:09

ubadub


1 Answers

Use productIterator, immediately followed by toArray:

(42, 3.14, "hello", true).productIterator.toArray

gives:

res0: Array[Any] = Array(42, 3.14, hello, true)

The type of the result shows the main reason why it's rarely used: in tuples, the types of the elements can be heterogeneous, in arrays they must be homogeneous, so that often too much type information is lost during this conversion. If you want to do this, then you probably shouldn't have stored your information in tuples in the first place.

There is simply almost nothing you can (safely) do with an Array[Any], except printing it out, or converting it to an even more degenerate Set[Any]. Instead you could use:

  • Lists of case classes belonging to a common sealed trait,
  • shapeless HLists,
  • a carefully chosen base class with a bit of inheritance,
  • or something that at least keeps some kind of schema at runtime (like Apache Spark Datasets)

they would all be better alternatives.

In the somewhat less likely case that the elements of the "tuples" that you are processing frequently turn out to have an informative least upper bound type, then it might be because you aren't working with plain tuples, but with some kind of traversable data structure that puts restrictions on the number of substructures in the nodes. In this case, you should consider implementing something like Traverse interface for the structure, instead of messing with some "tuples" manually.

like image 165
Andrey Tyukin Avatar answered Sep 10 '26 19:09

Andrey Tyukin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!