Scala:从seq到元组

时间:2018-07-05 08:47:46

标签: scala tuples

通过以下操作将元组转换为List / Seq非常容易:

myTuple.productIterator.toSeq

但是反向操作如何(出于好奇而已)。下面的代码有效,但是非常丑陋。

def arrayToTuple(a: Seq[Any]) = a.size match {
    case  1 => (a(0))
    case  2 => (a(0), a(1))
    case  3 => (a(0), a(1), a(2))
    case  4 => (a(0), a(1), a(2), a(3))
    case  5 => (a(0), a(1), a(2), a(3), a(4))
    case  6 => (a(0), a(1), a(2), a(3), a(4), a(5))
    case  7 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6))
    case  8 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7))
    case  9 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8))
    case 10 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9))
    case 11 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10))
    case 12 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11))
    case 13 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12))
    case 14 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13))
    case 15 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14))
    case 16 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15))
    case 17 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16))
    case 18 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17))
    case 19 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17), a(18))
    case 20 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17), a(18), a(19))
    case 21 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17), a(18), a(19), a(20))
    case 22 => (a(0), a(1), a(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10), a(11), a(12), a(13), a(14), a(15), a(16), a(17), a(18), a(19), a(20), a(21))
    case  _ => (0)
  }

1 个答案:

答案 0 :(得分:2)

这在Scala 2.X中是不可能的,因为元组的每个长度都是不同的类型,并且元组的每个元素都具有不同的类型。因此,很难编写一个将任何类型的值附加到任何类型的元组的函数。

但是,为了满足您的好奇心,这是Scala 3的一项待定功能。

  

具有任意数量元素的双胞胎被视为嵌套对的序列。例如。 (a, b, c)(a, (b, (c, ())))的简写。这样一来,我们就可以将最大元组长度的当前限制降低到22,并且允许类似于HList当前操作的元组上的通用程序。

请参见http://dotty.epfl.ch/docs/reference/overview.html