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)
The following might be shorter
dbQuery.copy(
userName = userName.getOrElse(dbQuery.userName),
address = address.getOrElse(dbQuery.address)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With