Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 807
montrivo Avatar asked Mar 03 '23 23:03

montrivo


1 Answers

The following might be shorter

dbQuery.copy(
  userName  = userName.getOrElse(dbQuery.userName),
  address = address.getOrElse(dbQuery.address)
)
like image 146
Mario Galic Avatar answered Mar 12 '23 08:03

Mario Galic