user48956
user48956

Reputation: 15820

Can tuples only be unpacked at variable declarations?

Why is

var a,b,c = (0,0,0)

allowed but not:

var a,b,c = (0,0,0)
(a,b,c) = (0,0,0)   <<< fails to compile
a,b,c = (0,0,0)    <<< fails to compile

Upvotes: 2

Views: 318

Answers (4)

Yann Moisan
Yann Moisan

Reputation: 8281

(0,0,0) is a Tuple3

scala> var a,b,c = (0,0,0)
a: (Int, Int, Int) = (0,0,0)
b: (Int, Int, Int) = (0,0,0)
c: (Int, Int, Int) = (0,0,0)

Each variable a, b, c is affected with the tuple

On contrary, when you do

scala> var (a,b,c) = (0,0,0)
a: Int = 0
b: Int = 0
c: Int = 0

a, b, c are simple Int, Scala uses the extractor method of the Tuple3 for deconstructing the object.

Upvotes: 1

som-snytt
som-snytt

Reputation: 39587

You're looking for the intupolator.

  var a, b, c = 0
  def pairing: Product = (11, 12)

  *(a, b) = pairing

Upvotes: 1

Randall Schulz
Randall Schulz

Reputation: 26486

The only way you can introduce a binding without using val or var is in a for comprehension or in pattern matching. The form you were going for, as Rex showed, is val (a, b, c) = (0, 1, 2). This is known as "irrefutable pattern matching," since there's no accommodation for a mis-tmatch between the right-hand side and the pattern after val. And it is not limited to TupleN. E.g.:

case class CC1(i: Int, d: Double, s: String)

val CC1(j, e, t) = CC1(1, 2.0, "three")
j: Int = 1
e: Double = 2.0
t: String = three

Upvotes: 0

Rex Kerr
Rex Kerr

Reputation: 167931

You probably mean

var (a,b,c) = (0,0,0)

since what you wrote is multiple assignment, not pattern matching.

And the reason is just stylistic. Scala favors working with immutable values but allows you to use mutable ones. Scala is--not only here--pretty short on handy features to help you work with mutable values.

That you can initialize vars with a pattern match should be considered a blessing in that context!

Upvotes: 3

Related Questions