scala Scala案例类更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24105479/
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
Scala case class update value
提问by bashan
I have a case class with 2 String members. I would like to update The second member later, so first I create an instance with String and None and later I load the data to the class and would like to update the second member with some value.
我有一个包含 2 个 String 成员的案例类。我想稍后更新第二个成员,所以首先我用 String 和 None 创建一个实例,然后我将数据加载到类中,并想用一些值更新第二个成员。
How can I do it?
我该怎么做?
回答by Jesper
Define the case class so that the second member is a var:
定义案例类,使第二个成员是 a var:
case class Stuff(name: String, var value: Option[String])
Now you can create an instance of Stuffand modify the second value:
现在您可以创建一个实例Stuff并修改第二个值:
val s = Stuff("bashan", None)
s.value = Some("hello")
However, making case classes mutable is probably not a good idea. You should prefer working with immutable data structures. Instead of creating a mutable case class, make it immutable, and use the copymethod to create a new instance with modified values. For example:
但是,使 case 类可变可能不是一个好主意。您应该更喜欢使用不可变的数据结构。与其创建可变 case 类,不如使其不可变,并使用该copy方法创建一个具有修改值的新实例。例如:
// Immutable Stuff
case class Stuff(name: String, value: Option[String])
val s1 = Stuff("bashan", None)
val s2 = s1.copy(value = Some("hello"))
// s2 is now: Stuff("bashan", Some("hello"))
回答by Robby Cornelissen
Case classes in Scala are preferably immutable. Use a regular class for what you're trying to achieve, or copy your case class object to a new one with the updated value.
Scala 中的案例类最好是不可变的。将常规类用于您要实现的目标,或将您的案例类对象复制到具有更新值的新对象。
回答by Paul
Let's say your case class looks like this:
假设您的案例类如下所示:
case class Data(str1: String, str2: Option[String]
First you create an instance setting the second string to None:
首先,您创建一个实例,将第二个字符串设置为None:
val d1 = Data("hello", None)
And now you create a new value by copying this object into a new one and replace the value for str2:
现在您通过将此对象复制到一个新对象并替换 str2 的值来创建一个新值:
val d2 = d1.copy(str2=Some("I finally have a value here"))
I would also consider the possibility that your case class is not the best representation of your data. Perhaps you need one class DataWithStr2that extends Data, and that adds another string that is always set. Or perhaps you should have two unrelated case classes, one with one string, and another with two.
我还会考虑您的案例类不是您数据的最佳表示的可能性。也许您需要一个DataWithStr2扩展类Data,并添加另一个始终设置的字符串。或者你应该有两个不相关的 case 类,一个有一个字符串,另一个有两个。

