Question

I have a Scala list. I can destructure the list into some variables thus:

var a :: b :: tail = myList
a should be ("A1")
b should be ("B1")
tail should be ('empty)

However, I do not seem to be able to reuse the same variables for another destructuring:

a :: b :: tail = anotherList
a should be ("A2")
b should be ("B2")
tail should be ('empty)

The compiler tells me that it expected a semi-colon but found an equals sign. Why is this? Is it impossible to use already-declared variables when destructuring? Am I doing something stupid?

Was it helpful?

Solution

Pattern extraction requires a case, val or var prefix or must occur within a for expression. Therefore, re-assigning the variables is not possible.


The Scala Language lists these cases in §§4.1 (values), 4.2 (variables), 6.19 (for-comprehensions) and 8.4 (pattern matching expressions)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top