Created
February 12, 2019 12:06
-
-
Save phiSgr/22eee33e697119317401076356764823 to your computer and use it in GitHub Desktop.
Prisms for scalapb, as `oneof` is tagged union
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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