Search code examples
scalacopylagom

how to copy a class inside of a state?


Its quite simple if all of the val in the State is basic data type. if we want to copy a specific value inside of it, it would just be

copy(specificValue = newValue)

but how if this specific value, is inside of a class? this is what I have tried but with no avail

copy(specificClass.specificValue = newValue)

should I instead create/copy this class outside, then make it like bellow?

copy(specificClass = newClass)


Solution

  • if you have

    
    case class Address(street: String, city: String)
    case class User(address: Address, name: String)
    
    val u = User(...)
    
    //to change the city to something else you would do
    
    val another = u.copy(address = u.address.copy(city = "New York") 
    
    

    This is cumbersome. I recommend using quicklens library which will allow you to write:

    
     import com.softwaremill.quicklens._
    
     val another = u.modify(_.address.city).setTo("New York")