是否可以在 Scala 中对变量进行元组赋值? [英] Is it possible to have tuple assignment to variables in Scala?
问题描述
可能的重复:
元组参数声明和赋值奇怪
在 Scala 中,可以通过以下方式对元组进行多变量赋值:
In Scala, one can do multiple-variable assignment to tuples via:
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)
我想在多变量赋值中重用 c
和 d
.这可能吗?
I'd like to reuse c
and d
in multiple-variable assignment. Is this possible?
推荐答案
这不仅仅是多变量赋值",而是全功能的模式匹配!
This isn't simply "multiple variable assignment", it's fully-featured pattern matching!
所以以下都是有效的:
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 _ =>
}
这篇关于是否可以在 Scala 中对变量进行元组赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!