在 Scala 中,如何重新分配元组值? [英] In Scala, how can I reassign tuple values?
问题描述
我正在尝试执行以下操作
I'm trying to do something like the following
var tuple = (1, "test")
tuple._2 = "new"
但是这不会编译它抱怨 val
However this does not compile it complains about val
推荐答案
您不能重新分配元组值.它们是故意不可变的:一旦你创建了一个元组,你就可以确信它永远不会改变.这对于编写正确的代码非常有用!
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")
或者如果您真的想使用 var 来包含元组:
or if you really want to use a var to contain the tuple:
var tuple = (1, "test")
tuple = tuple.copy(_2 = "new")
或者,如果您真的、真的希望单独更改您的值,您可以改用 case 类(可能带有隐式转换,以便您可以在需要时获得元组):
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"
这篇关于在 Scala 中,如何重新分配元组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!