Multiple assignment of non-tuples in scala Multiple assignment of non-tuples in scala arrays arrays

Multiple assignment of non-tuples in scala


All you need to do is make your val side (left of the =) compatible with your initializer (right of the =):

scala> val Array(x, y, z) = "XXX,YYY,ZZZ".split(",")x: java.lang.String = XXXy: java.lang.String = YYYz: java.lang.String = ZZZ

As you expected, a scala.MatchError will be thrown at runtime if the array size don't match (isn't 3, in the above example).


Since your string can have arbitrary contents, the result cannot be guaranteed to have a 2-tuple-form by the type-system (and no conversion would make sense at all). Therefore you'll have to deal with sequences (like arrays) anyway.

Thankfully there are right-ignoring sequence patterns which allow you to match the result values conveniently nevertheless.

val Seq(x, y, _ @ _*) = "a b".split(" ")


scala> val Array(x, y, _*) = "a b" split " "x: java.lang.String = ay: java.lang.String = b