是否可以对 Scala 中的变量进行元组赋值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6196678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to have tuple assignment to variables in Scala?
提问by Heinrich Schmetterling
Possible Duplicate:
Tuple parameter declaration and assignment oddity
可能的重复:
元组参数声明和赋值奇怪
In Scala, one can do multiple-variable assignment to tuples via:
在 Scala 中,可以通过以下方式对元组进行多变量赋值:
val (a, b) = (1, 2)
But a similar syntax for assignment to variables doesn't appear to work. For example I'd like to do this:
但是类似的赋值给变量的语法似乎不起作用。例如,我想这样做:
var (c, d) = (3, 4)
(c, d) = (5, 6)
I'd like to reuse cand din multiple-variable assignment. Is this possible?
我想重用c和d多变量赋值。这可能吗?
回答by Kevin Wright
This isn't simply "multiple variable assignment", it's fully-featured pattern matching!
这不仅仅是“多变量赋值”,它是功能齐全的模式匹配!
So the following are all valid:
所以以下都是有效的:
val (a, b) = (1, 2)
val Array(a, b) = Array(1, 2)
val h :: t = List(1, 2)
val List(a, Some(b)) = List(1, Option(2))
This is the way that pattern matching works, it'll de-construct something into smaller parts, and bind those parts to new names. As specified, pattern matching won't bind to pre-existing references, you'd have to do this yourself.
这就是模式匹配的工作方式,它将一些东西分解成更小的部分,并将这些部分绑定到新名称。正如指定的那样,模式匹配不会绑定到预先存在的引用,您必须自己执行此操作。
var x: Int = _
var y: Int = _
val (a, b) = (1, 2)
x = a
y = b
// or
(1,2) match {
case (a,b) => x = a; y = b
case _ =>
}
回答by Kim Stebel
I don't think what you want is possible, but you can get something quite similar with the "magical" update method.
我不认为你想要什么是可能的,但你可以获得与“神奇”更新方法非常相似的东西。
case class P(var x:Int, var y:Int) {
def update(xy:(Int, Int)) {
x = xy._1
y = xy._2
}
}
val p = P(1,2)
p() = (3,4)

