Scala 元组解构 [英] Scala Tuple Deconstruction
问题描述
我是 Scala 的新手,遇到了一个让我烦恼的小问题.
I am new to Scala, and ran across a small hiccup that has been annoying me.
并行初始化两个变量效果很好:var (x,y) = (1,2)
Initializing two vars in parallel works great: var (x,y) = (1,2)
但是我找不到并行分配新值的方法:(x,y) = (x+y,y-x)//invalid syntax
However I can't find a way to assign new values in parallel: (x,y) = (x+y,y-x) //invalid syntax
我最终写成这样:val xtmp = x+y;y = x-y;x = xtmp
我意识到编写函数式代码是避免这种情况的一种方法,但在某些情况下,var 更有意义.
I realize writing functional code is one way of avoiding this, but there are certain situations where vars just make more sense.
我有两个问题:
1) 有没有更好的方法来做到这一点?我错过了什么吗?
1) Is there a better way of doing this? Am I missing something?
2) 不允许真正并行赋值的原因是什么?
2) What is the reason for not allowing true parallel assignment?
推荐答案
遗憾的是,您不能在 Scala 中进行多项作业.但是您可以使用元组,如果它们适合您的问题:
Unfortunately, you cannot do multiple assignments in Scala. But you may use tuples, if they fit your problem:
scala> var xy = (1,2)
xy: (Int, Int) = (1,2)
scala> xy = (xy._1 + xy._2, xy._2 - xy._1)
xy: (Int, Int) = (3,1)
这样,xy
是一个有两个值的元组.第一个值可以使用 xy._1
访问,第二个值可以使用 xy._2
访问.
This way, xy
is one tuple with two values. The first value can be accessed using xy._1
, the second one using xy._2
.
这篇关于Scala 元组解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!