简体   繁体   中英

Play2 Scala models - merge objects

I'm using Play2+Scala+ReactiveMongo to build a web application. Since mongodb doesn't require all documents to have the same structure, I make a large use of case classes with Options as parameters to implement models. For example:

case class PersonInfo(address: Option[String],
                      telephone: Option[String],
                      age: Option[Int],
                      job: Option[String])
case class Person(id: UUID, name: String, info: PersonInfo)

Now suppose I want to merge two PersonInfo objects, for example in a update function. I do right now is:

val updPInfo = old.copy(address = new.address orElse address,
                        telephone = new.telephone orElse telephone,
                        age = new.age orElse age,
                        job = new.job orElse job)

This way I have an object that has new values where they were specified by the new object and old values for the remaining ones.

This actually works fine, but it is bit ugly to see when the list of parameters grows.

Is there a more elegant way to do that?

If the only place you need this is in mongo, you can do it, like this:

collection.
      update(
          Json.obj("_id" -> id),
          Json.obj("$set" -> Json.toJson(new))
      )

That way you'll have correct presentation in DB, which you can read and use afterwards.

or

If you need it in Scala, you can merge 2 Json presentations:

val merged = Json.toJson(old).deepMerge(new).as[PersonInfo]

Which is not quite better, then what you are doing now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM