In this post we’ll look at
BooleanOps and the goodies it provides to work with
Booleans. As always, we’ll go straight to examples.
@ import scalaz._
As the comment for
Executes the given side-effect if this boolean value is false.
A mnemonic to remember the working is: “Unless the value is true, execute the side-effecting function”.
// executes the given side-effect if this boolean value is true
The “opposite” of
when which executes the function when the value is true. As the comment for
Executes the given side-effect if this boolean value is true.
A mnemonic to remember the working is: “When the value is true, execute the side-effecting function”.
Folding a Boolean
@ t fold[String]("this will be returned when true", "this will be returned when false")
fold lets you decide what value to return depending on whether it is true or false.
Converting to an Option
@ t option "this will create a Some() with this string in it"
option lets us convert a
Boolean into an
Option in a type-safe manner. A true results in a
Some containing the value passed to
option whereas a false results in an
Option of whatever the type of the argument is.
@ t ? "true" | "false"
Scalaz also provides a ternary operator to work with
Booleans. The ternary operator is actually a combination of
? is the conditional operator that results in the creation of an object of
| is a method of that object.
@ t ?? List(1, 2, 3)
?? returns the given argument if the value is true, otherwise, the zero element for the type of the given argument. In our case, the “zero” element for
List is an empty
@ t !? List(1, 2, 3)
!? is the opposite of
?? and returns the argument if the value is false or the zero element otherwise.
This brings us to the end of our post on
BooleanOps. There’s a lot more functions provided but I’ve chosen to cover those which I feel will be the most useful.