It is very easy to convert a tuple into a List/Seq by doing:
myTuple.productIterator.toSeq
But what about the reverse operation (just out of curiosity). The code below works, but is quite ugly...
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)
}
This is not possible in Scala 2.X because each length of tuple is a different type and each element of a tuple has a different type. So it would be difficult to write a function to append a value of any type to a tuple of any type.
But to satisfy your curiosity, this is a pending feature of Scala 3:
Tuples with arbitrary numbers of elements are treated as sequences of nested pairs. Eg
(a, b, c)
is shorthand for(a, (b, (c, ())))
. This lets us drop the current limit of 22 for maximal tuple length and it allows generic programs over tuples analogous to what is currently done forHList
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.