Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign same value to multiple variables in Scala

Tags:

scala

I have 3 variables that have already been initialized, and I want to assign a new value to all three of them. e.g.

var a = 1
var b = 2
var c = 3

and I want to reassign them to the same value e.g.

a = b = c = 4

But the above expression is invalid. Is there a right way to do this in Scala?

like image 208
Aashish Dattani Avatar asked Mar 15 '19 08:03

Aashish Dattani


1 Answers

It is possible to slightly shorten the var definition code as follows

var (a, b, c) = (1, 2, 3)

This works because of extractor objects in scala. A tuple of 3 is extracted into 3 components it was created with.

But following does not work becase the extraction is applied on val or var definitions.

(a, b, c) = (4, 4, 4)
like image 105
Ivan Stanislavciuc Avatar answered Nov 09 '22 22:11

Ivan Stanislavciuc