2014-07-10 44 views
0

我需要創建一個元組,但是此元組的大小需要根據變量值在運行時更改。我不能在scala中這樣做。所以我創建了一個數組:將可變長度數組轉換爲scala中的元組

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

如何將數組轉換爲元組。這可能嗎?我是一個斯卡拉新手。

+0

是大小將在運行變化的唯一的事情?如何在你的元組中的項目類型?如你的例子所示,它會一直是'String'嗎? – vptheron

+2

元組根據定義是一個異構元素固定的元素。如果您需要動態數量的字符串,則可以使用任何類型的集合。你爲什麼要把它轉換成「元組」? –

+0

我需要一個元組,因爲我需要將一個元組提供給另一個類的方法,這是我無法控制的。是的,這個元組的類型是String – user2773013

回答

2

爲了創建一個元組,你必須知道預期的大小。假設你有這個,那麼你可以做這樣的事情:

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)