How would I express a chained assignment in Scala?
Asked Answered
F

5

8

How would I express the following java code in scala?

a = b = c;

By the way, I'm re-assigning variables (not declaring).

Finch answered 14/3, 2010 at 13:38 Comment(0)
C
13

The closest shortcut syntax in Scala can only be used when you declare a var or val.

scala> val c = 1  
c: Int = 1

scala> val a, b = c
a: Int = 1
b: Int = 1

From the Scala Reference, Section 4.1

A value declaration val x1 , ... , xn: T is a shorthand for the sequence of value declarations val x1: T ; ...; val xn: T. A value definition val p1, ..., pn = e is a shorthand for the sequence of value definitions val p1 = e ; ...; val pn = e . A value definition val p1, ... , pn : T = e is a shorthand for the sequence of value definitions val p1 : T = e ; ...; val pn: T = e .

This doesn't work for re-assignement to a var. The C/Java style doesn't work for reasons explained here: What is the Motivation for Scala Assignment Evaluating to Unit

Cumulus answered 14/3, 2010 at 13:58 Comment(1)
Note that the expression on the right-hand-side will be evaluated several times (once per a variable): e.g. a and b in val a, b = new Object will refer to different objects.Swear
S
5

Using the fact that the left-hand-side of an assignment is syntactically a pattern. (See PatVarDef > PatDef > Pattern2 in SLS.)

a = b = 5

scala> val a@b = 5
a: Int = 5
b: Int = 5

x = y = z = new Object

scala> var x@(y@z) = new Object
x: java.lang.Object = java.lang.Object@205144
y: java.lang.Object = java.lang.Object@205144
z: java.lang.Object = java.lang.Object@205144

Note that the expression on the right-hand-site is evaluated only once.

Unfortunately, this syntax doesn't work for reassigning (so for x = y = value you still have to do x = value; y = x).

See also [scala-language] Chained assignment in Scala

Swear answered 13/2, 2012 at 4:5 Comment(0)
F
1

The "return type" of the expression (assignment) b = c is Unit, I'm afraid, which means this syntax is not valid.

Freeload answered 14/3, 2010 at 13:51 Comment(0)
E
1
b = c; a = b

Awkward, I know. That's Scala pretty much telling you "don't do that". Consider it the Scala version of Python's space identation for block delimitation.

Extricate answered 14/3, 2010 at 19:41 Comment(0)
W
-1
val b = c
val a = b

You can't write

val a = b = c

since that defines an expression

Watershed answered 14/3, 2010 at 13:44 Comment(2)
or var, when the variable is variable and not final.Diazo
Isn't there a shorthand? It seems stupid having to write b = c; a = bFinch

© 2022 - 2024 — McMap. All rights reserved.