I’d like to use val to declare multiple variable like this:
val a = 1, b = 2, c = 3
But for whatever reason, it’s a syntax error, so I ended up using either:
val a = 1
val b = 2
val c = 3
or
val a = 1; val b = 2; val c = 3;
I personally find both options overly verbose and kind of ugly.
Is there a better option?
Also, I know Scala is very well thought-out language, so why isn’t the val a = 1, b = 2, c = 3 syntax allowed?
The trivial answer is to declare them as tuples:
What might be interesting here is that this is based on pattern matching. What is actually happens is that you are constructing a tuple, and then, through pattern matching, assigning values to
a,bandc.Let’s consider some other pattern matching examples to explore this a bit further:
Just as a side note, the
rndexample, in particular, may be written more simply, and without illustrating pattern matching, as shown below.