scalaoption-typecase-class

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?


Solution

  • 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"))