In this post we’ll look at OptionOps
and the goodies it provides to work with Option
s. We’ll jump straight into examples.
Creating Options
1 | @ import scalaz._ |
Extracting Values
1 | // using unary ~ operator |
The unary ~
extracts the value from the Option
or returns the zero value for that type. For example, in case of Int
it’ll return the value in the Option
or return 0. The some{ .. } none { .. }
construct lets you specify what value to return in case of Some
and None
. I am multiplying the value by 2 and thus returning 26. As you can see, Scalaz provides with more expressive and type-safe way to create and extract values from Option
.
Notice that the type of all the resulting variables is Option
instead of Some
or None
. This is more type-safe than using None
because you’d get None.type
, and the type inferencer would allow the type to be Option[Int]
or Option[String]
whereas none[Int]
is guaranteed to be an Option[Int]
. The type inferencer will enforce this.
Miscellaneous
1 | // we'll have fun with these values |
Scalaz provides us with a disjunction which is a replacement for Scala Either
. I’ve only introduced disjunction here and will cover it later in a post of its own. Trying to convert a None
to a right disjunction doesn’t work. We get back a left disjunction as indicated by -\/
. Similarly, converting a Some
to right disjunction works, as indicated by \/-
. Scalaz also provides a ternary operator to work with Option
s.
Conclusion
This sums up, non-exhaustively, how we can use the convenience methods that Scalaz provides on top of Option
s that lets us code in more expressive and type-safe way.