Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case class update value

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.

How can I do it?

like image 305
bashan Avatar asked Jun 08 '14 11:06

bashan


3 Answers

Define the case class so that the second member is a var:

case class Stuff(name: String, var value: Option[String])

Now you can create an instance of Stuff and modify the second value:

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 copy method to create a new instance with modified values. For example:

// 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"))
like image 138
Jesper Avatar answered Sep 22 '22 06:09

Jesper


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:

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:

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 DataWithStr2 that 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.

like image 28
Paul Avatar answered Sep 20 '22 06:09

Paul


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.

like image 22
Robby Cornelissen Avatar answered Sep 24 '22 06:09

Robby Cornelissen