In Scala, how can I reassign tuple values?

前端 未结 2 1610
傲寒
傲寒 2020-12-06 01:42

I\'m trying to do something like the following

var tuple = (1, \"test\")
tuple._2 = \"new\"

However this does not compile it complains abou

相关标签:
2条回答
  • 2020-12-06 01:54

    You can wrapper the component(s) you need to modify in a case class with a var member, like:

    case class Ref[A](var value: A)
    
    var tuple = (Ref(1), "test")
    tuple._1.value = 2
    println(tuple._1.value) // -> 2
    
    0 讨论(0)
  • 2020-12-06 02:07

    You can't reassign tuple values. They're intentionally immutable: once you have created a tuple, you can be confident that it will never change. This is very useful for writing correct code!

    But what if you want a different tuple? That's where the copy method comes in:

    val tuple = (1, "test")
    val another = tuple.copy(_2 = "new")
    

    or if you really want to use a var to contain the tuple:

    var tuple = (1, "test")
    tuple = tuple.copy(_2 = "new")
    

    Alternatively, if you really, really want your values to change individually, you can use a case class instead (probably with an implicit conversion so you can get a tuple when you need it):

    case class Doublet[A,B](var _1: A, var _2: B) {}
    implicit def doublet_to_tuple[A,B](db: Doublet[A,B]) = (db._1, db._2)
    val doublet = Doublet(1, "test")
    doublet._2 = "new"
    
    0 讨论(0)
提交回复
热议问题