converting array of variable length to tuple in sc

2019-08-31 04:12发布

问题:

I need to create a tuple but this tuple's size need to change at run time based on variable value. I can't really do that in scala. So i created an array:

val temp:Array[String] = new Array[String](x)

How do I convert the array to tuple. is this possible? i'm a scala newbie.

回答1:

In order to create a tuple, you have to know the intended size. Assuming you have that, then you can do something like this:

val temp = Array("1", "2")
val tup = temp match { case Array(a,b) => (a,b) }
// tup: (String, String) = (1,2)

def expectsTuple(x: (String,String)) = x._1 + x._2
expectsTuple(tup)

And that allows you to pass the tuple to whatever function expects it.


If you want to get fancier, you can define .toTuple methods:

implicit class Enriched_toTuple_Array[A](val seq: Array[A]) extends AnyVal {
  def toTuple2 = seq match { case Array(a, b) => (a, b); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple2: Array(${x.mkString(", ")})") }
  def toTuple3 = seq match { case Array(a, b, c) => (a, b, c); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple3: Array(${x.mkString(", ")})") }
  def toTuple4 = seq match { case Array(a, b, c, d) => (a, b, c, d); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple4: Array(${x.mkString(", ")})") }
  def toTuple5 = seq match { case Array(a, b, c, d, e) => (a, b, c, d, e); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple5: Array(${x.mkString(", ")})") }
}

This lets you do:

val tup = temp.toTuple2
// tup: (String, String) = (1,2)


回答2:

Ran into a similar problem. I hope this helps.

(0 :: 10 :: 50 :: Nil).sliding(2, 1).map( l => (l(0), l(1)))

Results:

List[(Int, Int)] = List((0,10), (10,50))


标签: scala