在scala中将可变长度的数组转换为元组

时间:2014-07-10 17:34:37

标签: scala

我需要创建一个元组,但是这个元组的大小需要在运行时根据变量值进行更改。我不能真的在scala中这样做。所以我创建了一个数组:

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

如何将数组转换为元组。这可能吗?我是斯卡拉新手。

2 个答案:

答案 0 :(得分:4)

要创建元组,您必须知道预期的大小。假设你有,那么你可以这样做:

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)

这允许您将元组传递给任何期望它的函数。


如果您想获得更好的感受,可以定义.toTuple方法:

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(", ")})") }
}

这可以让你:

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

答案 1 :(得分:0)

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))