Skip to content

Instantly share code, notes, and snippets.

@phiSgr
Created February 12, 2019 12:06
Show Gist options
  • Save phiSgr/22eee33e697119317401076356764823 to your computer and use it in GitHub Desktop.
Save phiSgr/22eee33e697119317401076356764823 to your computer and use it in GitHub Desktop.
Prisms for scalapb, as `oneof` is tagged union
import scalapb.GeneratedOneof
import scalapb.lenses.{Lens, Mutation}
trait Prism[OneOf, Case] {
def down(o: OneOf): Option[Case]
def up(c: Case): OneOf
}
implicit class OneOfLens[A, OneOf <: GeneratedOneof](l: Lens[A, OneOf]) {
def mutateCase[B](p: Lens[A, OneOf] => Prism[OneOf, B])(m: Lens[B, B] => Mutation[B]): Mutation[A] = a => {
val prism = p(l)
val oneOf = l.get(a)
prism.down(oneOf) match {
case Some(b) =>
val mutation = m(Lens.unit)
val newOneOf = prism.up(mutation(b))
l.set(newOneOf)(a)
case None => a
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment