6

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?

1
  • As Andrey explains, this is definitely not "common" at all; you should never need to do this (except perhaps under highly unusual circumstances). Commented Feb 15, 2019 at 20:14

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree that mixing tuples and arrays like this is bad practice, but it was for a specific issue where I was bound by certain constraints not under my control. Anyways, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.