I recently came across another elegant use of the type class pattern, so I thought I'd share it with here.
Developers at a client recently asked about the following code:
What is that ~x there?
It's a unary method call.
An example of a unary method is -, as in -1. - is actually defined in scala.Numeric like this:
So -1 is actually 1.unary_-. The unary_ part can be omitted when used in prefix form. Note that the only identifiers that can be used as prefix operators are +, -, !, and ~.
So the answer to the question is: its a unary method defined … somewhere:
What does ~ do to options?
In Scalaz its a method that returns the value contained in an Option, or a default Zero for the Option's type. For example, ~Some(1) returns 1, ~None (for an Option[Int]) will return 0.
But how does our unary method find an appropriate Zero instance?
So there it is, a unary method enriching an Option via an implicit view which requires an implicit Zero instance for the Option's enclosed type.
Scalaz provides all the machinery to do this so all you need to do is use it. If you need to modify the defaults then you can provide your own implicit Zero instances and import them. The implicit resolution rules will ensure that your instances will be found before the defaults if they are imported or placed in the companion object of your classes.
If you want to learn more about this kind of thing have a look at the other blogs in this series of Small Examples.
If you would like a course on Scala, look no further than Underscore.
We encourage discussion of our blog posts on our Gitter channel.
Please review our Community Guidelines before posting there.
We encourage discussion in good faith, but do not allow combative, exclusionary, or harassing behaviour.
If you have any questions, contact us!