0

I have an Array which is a result of a split function. Now I want all the elements of this array to be the elements of a tuple.

The number of elements are not more than 22.

Bishamon Ten
  • 479
  • 1
  • 6
  • 20
  • 3
    Are you sure that the tuple will always have a fixed number of elements? Then you can write a simple auxiliar method. If not, how would you expect to use it? If the concrete type of the tuple will be different given some runtime values. – Luis Miguel Mejía Suárez Feb 09 '20 at 14:36
  • 2
    Well, to be honest, converting array to tuple, sounds like not the best idea, for a variety of reasons. Could you please share what you want to achieve at the end and why would you need it? Maybe there is better approach. – Ivan Kurchenko Feb 09 '20 at 14:47
  • Duplicated? https://stackoverflow.com/questions/14722860/convert-a-scala-list-to-a-tuple – Cesar A. Mostacero Feb 10 '20 at 20:58

1 Answers1

1

Unfortunately you can't do that in a type-safe manner. Tuple arity must be known in the compile time. Your array's length is known only in runtime since collections have arbitrary lengths.

You probably want to do something with this tuples afterwards. Problem is you need to write a code that handles all tuple cases such as;

array match {
  case Array(first)=> ???
  case Array(first, second) => ???
  case Array(first, second, third) => ???
      ...
  case Array(first, second, third, fourth, fifth, sixth, seventh, .... twentysecond) => ???
  case _ => // What to do now?
}

It is like this because we don't know what could be the outcome of this array -> tuple operation in compile-time, so we cover all the cases.

If we know how many elements our array has in the compile time we can use Shapeless to do something like this below, like answered in another question

import shapeless._
import HList._
import syntax.std.traversable._

val x = List(1, 2, 3)
val y = x.toHList[Int::Int::Int::HNil]
val z = y.get.tupled
Deliganli
  • 221
  • 2
  • 10
  • yes, we can know the size of the array before creating an Array. Does this allow to easily create a tuple form array? – Bishamon Ten Feb 16 '20 at 14:28