在 Scala 中,如何重新分配元组值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7142838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:22:48  来源:igfitidea点击:

In Scala, how can I reassign tuple values?

scala

提问by deltanovember

I'm trying to do something like the following

我正在尝试执行以下操作

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

However this does not compile it complains about val

然而,这不会编译它抱怨 val

回答by Rex Kerr

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 来包含元组:

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 类(可能使用隐式转换,以便您可以在需要时获得元组):

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"

回答by Colliot

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

您可以使用var成员在案例类中包装您需要修改的组件,例如:

case class Ref[A](var value: A)

var tuple = (Ref(1), "test")
tuple._1.value = 2
println(tuple._1.value) // -> 2