也许您可以使用modifyF
而不是modify
返回 an Option
,这样您就不必检查是否有变化。
例如 :
import monocle.Lens
import monocle.macros.GenLens
import scalaz.std.option._
case class Person(name: String, address: Address)
case class Address(street: String, number: Int)
val addressL: Lens[Person, Address] = GenLens[Person](_.address)
val streetL: Lens[Address, String] = GenLens[Address](_.street)
val changePersonsStreet: Person => Option[Person] =
(addressL composeLens streetL).modifyF[Option] { street =>
// only change street name if first letter comes before 'N'
street.headOption.filter(_.toString.capitalize < "N").map(_ => "New Street")
// or any other condition
// if (theSunIsUp) Some("changed street name") else None
} _
val alice = Person("Alice", Address("Main Street", 1))
val alice2: Option[Person] = changePersonsStreet(alice)
// Some(Person(Alice,Address(New Street,1)))
// -> modified, no need to check
val alice3 = alice2.flatMap(changePersonsStreet)
// None
// -> not modified