Skip to content

Instantly share code, notes, and snippets.

@coltfred
Last active December 25, 2015 21:39
Show Gist options
  • Save coltfred/7044541 to your computer and use it in GitHub Desktop.
Save coltfred/7044541 to your computer and use it in GitHub Desktop.
//Methods returning an Option of Boolean(or generally any Monad of Boolean)
def one: Option[Boolean] = Some(true)
def two: Option[Boolean] = Some(true)
//I'd like to be able to write something like the following.
if (!one && two) {
}
//This is ugly
one.flatMap { oneBool =>
if (!oneBool) {
two
} else {
None
}
}.getOrElse(false)
//I could also do this, but it still seems a bit ugly
one match {
case Some(false) => two
case x => x
}.getOrElse(false)
//Alternately I could do the following
implicit val andMonoid = Monoid.instance[Boolean]((a, b) => a && b, true)
if ((one.map(!_) |+| two).getOrElse(false)) {
//Do stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment