How would I express a chained assignment in Scala?

后端 未结 5 1568
南方客
南方客 2021-01-05 01:05

How would I express the following java code in scala?

a = b = c;

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

5条回答
  •  醉话见心
    2021-01-05 01:33

    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

提交回复
热议问题