jeudi 16 mai 2019

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(d.userName = u)
  .ifDefined(address)((d, a) => d.copy(d.address = a)

Aucun commentaire:

Enregistrer un commentaire