Created
July 21, 2021 22:44
-
-
Save afsalthaj/898ad9d9da62ce4b0f95b33135271645 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
trait OptionSyntax { | |
implicit class OptionOps[A](s: Option[A]) { | |
def ifExists[F[_], B](f: A => F[B]): PartialOption[F, B] = | |
s match { | |
case Some(value) => new PartialOption(Some(f(value))) | |
case None => new PartialOption(None) | |
} | |
} | |
} | |
object OptionSyntax extends OptionSyntax { | |
class PartialOption[F[_], A](f: Option[F[A]]) { | |
def orElse(g: F[A]): F[A] = | |
f.fold(g)(identity) | |
} | |
} | |
// Usage | |
def transform[A, B]: Option[A => B] = None | |
val data: A = ??? | |
optionalTransformation | |
.ifExists(transform => IO.delay(transform(data)) | |
.orElse(IO.pure(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment