Home > Enterprise >  Convert an array with n elements to a tuple with n elements in Scala
Convert an array with n elements to a tuple with n elements in Scala

Time:04-28

I have an array of elements (numbers in my case)

var myArray= Array(1, 2, 3, 4, 5, 6)
//myArray: Array[Int] = Array(1, 2, 3, 4, 5, 6)

and I want to obtain a tuple than contain all of them:

var whatIwant= (1,2,3,4,5,6)
//whatIwant: (Int, Int, Int, Int, Int, Int) = (1,2,3,4,5,6)

I tried the following code but it doesn't work:

var tuple = myArray(0)
for (e <- myArray) 
{
    var tuple = tuple :  e
}
//error: recursive variable tuple needs type

CodePudding user response:

The number of elements of a tuple is not infinitely superimposed. In earlier versions, there were only 22 at most. Scala treats tuples with different numbers of elements as different classes. So you can't add elements like a list. Apart from utilizing metaprogramming techniques such as reflection, tuple objects may only be generated explicitly.

CodePudding user response:

The trivial answer is this:

val whatIwant =
  myArray match {
    case Array(a, b, c, d, e, f) => (a, b, c, d, e, f)
    case _                       => (0, 0, 0, 0, 0, 0)
  }

If you want to support different numbers of element in myArray then you are in for a world of pain because you will lose all the type information associated with a tuple.

If you are using Spark you should probably use its mechanisms to generate the data you want directly rather than converting to Array first.

  • Related