montrivo
montrivo

Reputation: 175

scala chained conditional mapping - `ifDefined` method

Is there a more concise way of conditionally mapping over a value like in:

val userName: Option[String] = Some("Bob")
val address: Option[String] = Some("Planet Earth")

val dbQuery = new Query()

val afterUserName = 
  userName.map(u => dbQuery.copy(userName = u))
    .getOrElse(dbQuery)

val modifiedQuery = 
  address.map(a => afterUserName.copy(address = a))
    .getOrElse(afterUserName)

I wish there was an ifDefined method available on all types like in the following block. This removes the .getOrElse(...) call.

dbQuery
  .ifDefined(userName)((d, u) => d.copy(userName = u)
  .ifDefined(address)((d, a) => d.copy(address = a)

Upvotes: 4

Views: 212

Answers (1)

Mario Galic
Mario Galic

Reputation: 48430

The following might be shorter

dbQuery.copy(
  userName  = userName.getOrElse(dbQuery.userName),
  address = address.getOrElse(dbQuery.address)
)

Upvotes: 7

Related Questions