Ecco un approccio relativamente senza caldaia che utilizza Shapeless. In primo luogo definiamo alcune versioni polimorfe delle funzioni rilevanti sul Option
:
import shapeless._
object orElser extends Poly1 {
implicit def default[A] = at[Option[A]] {
oa => (o: Option[A]) => oa orElse o
}
}
object getOrElser extends Poly1 {
implicit def default[A] = at[Option[A]] {
oa => (a: A) => oa getOrElse a
}
}
ti rappresentano un aggiornamento come un HList
dove ogni elemento è un Option
, e possiamo scrivere un metodo append
che ci permette di aggiungere due aggiornamenti :
import UnaryTCConstraint._
def append[U <: HList: *->*[Option]#λ, F <: HList](u: U, v: U)(implicit
mapper: MapperAux[orElser.type, U, F],
zipper: ZipApplyAux[F, U, U]
): U = v.map(orElser).zipApply(u)
E finalmente possiamo scrivere il nostro metodo update
stesso:
def update[T, L <: HList, F <: HList, U <: HList](t: T, u: U)(implicit
iso: Iso[T, L],
mapped: MappedAux[L, Option, U],
mapper: MapperAux[getOrElser.type, U, F],
zipper: ZipApplyAux[F, L, L]
) = iso from u.map(getOrElser).zipApply(iso to t)
Ora abbiamo bisogno solo un po 'di boilerplate (in the future questo non sarà necessario, grazie a inference-driving macros):
implicit def pcIso =
Iso.hlist(PropositionContent.apply _, PropositionContent.unapply _)
Faremo anche definire un alias per questo specifico tipo di aggiornamento (che non è strettamente necessario, ma renderà i seguenti esempi un po 'più conciso):
type PCUpdate = Option[String] :: Option[String] :: HNil
E infine:
scala> val pc = PropositionContent("some title", "some content")
pc: PropositionContent = PropositionContent(some title,some content)
scala> val u1: PCUpdate = Some("another title") :: None :: HNil
u1: PCUpdate = Some(another title) :: None :: HNil
scala> val u2: PCUpdate = Some("newest title") :: Some("new content") :: HNil
u2: PCUpdate = Some(newest title) :: Some(new content) :: HNil
scala> append(u1, u2)
res0: PCUpdate = Some(newest title) :: Some(new content) :: HNil
scala> update(pc, append(u1, u2))
res1: PropositionContent = PropositionContent(newest title,new content)
Quale è w cappello che volevamo
suggerimento: https://blog.stackmob.com/2012/02/an-introduction-to-lenses-in-scalaz/ –
E i tipi di alias? – sschaef
intendi 'type CompleteProposistionContent = PropositionContent [Id]'? – jwinandy