Scala Tuple Deconstruction

前端 未结 2 461
你的背包
你的背包 2020-12-11 14:26

I am new to Scala, and ran across a small hiccup that has been annoying me.

Initializing two vars in parallel works great: var (x,y) = (1,2)

How

相关标签:
2条回答
  • 2020-12-11 15:09

    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)
    

    This way, xy is one tuple with two values. The first value can be accessed using xy._1, the second one using xy._2.

    0 讨论(0)
  • 2020-12-11 15:09

    Scala has 2 types of variables: vals and vars. Vals are similar to Java's final variables, so as far as I understand from what you're asking, the only way to assign new values in parallel to vals is by:

    scala> val (x, y) = (1, 2);
    

    or

    scala> val s = (3, 4);
    s: (Int, Int) = (3,4)
    
    scala> s._1
    res1: Int = 3
    
    scala> s._2
    res2: Int = 4
    
    0 讨论(0)
提交回复
热议问题