Is it possible to have tuple assignment to variables in Scala? [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-11-27 19:35:40

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 _ =>
}

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!