In this post we’ll look at BooleanOps
and the goodies it provides to work with Boolean
s. As always, we’ll go straight to examples.
Unless
1 | @ import scalaz._ |
As the comment for unless
states:
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”.
When
1 | // executes the given side-effect if this boolean value is true |
The “opposite” of unless
is when
which executes the function when the value is true. As the comment for when
states:
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
1 | @ 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
1 | @ 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.
Ternary Operator
1 | @ t ? "true" | "false" |
Scalaz also provides a ternary operator to work with Boolean
s. The ternary operator is actually a combination of ?
and |
. ?
is the conditional operator that results in the creation of an object of Conditional
and |
is a method of that object.
Miscellaneous
1 | @ 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 List
.
1 | @ t !? List(1, 2, 3) |
!?
is the opposite of ??
and returns the argument if the value is false or the zero element otherwise.
Conclusion
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.