In Scala tuples can be unpacked:
val colors = ("red", "green")
val (colorA, colorB) = colors
Python also provides a way to unpack tuples, and a similar way for lists
colors = ['red', 'green']
(colorA, colorB) = colors
Is there an equivalent for Scala Sequences ?
val colors = Seq("red", "green")
val (colorA, colorB) = colors // Raises a compilation error
If not, why is it not possible ?
CodePudding user response:
scala> val colors = Seq("red", "green")
val colors: Seq[String] = List(red, green)
scala> val Seq(ca, cb) = colors
val ca: String = red
val cb: String = green
And more:
Welcome to Scala 3.1.3-RC2 (17.0.3, Java Java HotSpot(TM) 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala> val colors = (1 to 8).map(i => s"c$i")
val colors: IndexedSeq[String] = Vector(c1, c2, c3, c4, c5, c6, c7, c8)
scala> val c1 : _ = colors // get head
val c1: String = c1
scala> val _ : c8 = colors // get last
val c8: String = c8
scala> val head : _ : last = colors
val head: String = c1
val last: String = c8
scala> val _ : snd : _ = colors // get second
val snd: String = c2
// note: the following code is for scala3(scala2 should be slightly change)
scala> val Seq(_, c2, _*) = colors // get second too
val c2: String = c2
scala> val init : tail = colors // split to head and remain
val init: String = c1
val tail: IndexedSeq[String] = Vector(c2, c3, c4, c5, c6, c7, c8)
CodePudding user response:
The secret you need to understand is that this statement is wrong:
In Scala tuples can be unpacked
There is no such thing as tuple unpacking in Scala.
Rather, value definitions can make use of pattern matching, i.e. the left-hand side of a value definition can be a pattern.
See Section 4.1 Value Declarations and Definitions of the Scala Language Specification:
Value definitions can alternatively have a pattern as left-hand side.
Since you can pattern match a Seq
, that means you can "unpack" it during value definition, because they are both the same thing, and you do it using the same syntax.
But it is important to understand that this is not "tuple unpacking" or "Seq
unpacking". This is not some specialized feature that only works with a small number of specialized types. It is just bog-standard pattern matching, and thus works with every that can be matched, i.e. every case class, every extractor object, every class with unapply
and unapplySeq
, every class with a constructor, etc.
So, if you know how to pattern match a Seq
, then you also know how to "unpack" a Seq
:
val Seq(colorA, colorB) = colors