Reputation: 175
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
Reputation: 48430
The following might be shorter
dbQuery.copy(
userName = userName.getOrElse(dbQuery.userName),
address = address.getOrElse(dbQuery.address)
)
Upvotes: 7