Scala multiple assignment to existing variable

前端 未结 5 726
独厮守ぢ
独厮守ぢ 2021-01-11 17:02

I can do something like

def f(): Tuple2[String, Long] = ...
val (a, b) = f()

What about if the variables are already existing? I\'m runnin

5条回答
  •  天命终不由人
    2021-01-11 17:50

    The workaround I found is this:

    // declare as var, not val
    var x = (1,"hello")  
    // x: (Int, String) = (1,hello)
    
    // to access first element
    x._1
    // res0: Int = 1
    
    // second element
    x._2
    // res1: String = hello
    
    // now I can re-assign x to something else
    x = (2, "world")
    // x: (Int, String) = (2,world)
    
    // I can only re-assign into x as long the types match
    // the following will fail
    
    x = (3.14, "Hmm Pie")
    :8: error: type mismatch;
     found   : Double(3.14)
     required: Int
           x = (3.14, "Hmm Pie")
    

提交回复
热议问题