initmax
initmax

Reputation: 395

scala copy update fields into case classes

I want to update some fields into case class. I have two objects c1 and c2. Want to update fields into c2 by c1

Implemented next solution. Updated with copy and if statement

case class Ex(id: Option[Long] = None, id2: Option[String] = None)
  {
    def updateFields(e: Ex) = {
      this.copy(
        id = if (e.id.isDefined) e.id else id,
        id2 = if (e.id2.isDefined) e.id2 else id2,
      )
    }
  }

Does any best practices for do this action?

BR!

Upvotes: 1

Views: 226

Answers (1)

Tyth
Tyth

Reputation: 1824

You can use Option.orElse method

  case class Ex(id: Option[Long] = None, id2: Option[String] = None) {
    def updateFields(e: Ex) = {
      this.copy(id = e.id.orElse(id), id2 = e.id2.orElse(id2))
    }
  }

Upvotes: 4

Related Questions