OK, you came to the conclusion that type-safety is good; it helps you get things done in a safer manner, at least for whatever you’re working on at the moment. So you started using types more than before to describe what a piece of code does without the need to run; in other words, to bring forward unwanted errors.
One of the first things you may have found quite handy when starting to use Scala Option
null
s.
Have a look at this piece of code for instance
if
getUser
User
From a pragmatic point of view, one would argue that Scala is all about scalability, and asynchronous programming is one of the fundamentals of scalability.
Instead of having some fancy keywords, magic and hiding things (like C# 5 and others), Scala has chosen a direct answer: Future
type; as a result, it’s more likely that you’ll see methods returning Future
Again, method signature explains everything. The only difference is that it’s async and the consumer map
We always see this kind of cool, small code samples in fancy programming languages, but real-world software is not that simple and isolated. You always need to combine things together and that is where those lovely code samples don’t look shiny anymore.
Consider the following example where we want to find the user country by its ID asynchronously:
Despite the expressiveness of the method signatures, the code is not as beautiful as before. Although there is a pattern here, it doesn’t look as smooth and as readable.
This is one of the most common situations for a developer who is new to functional programming where a library like Cats comes in handy.
OptionT
Future
User
(OptionT[Future, User]
). This provides more abstraction. Let’s rewrite the above sample with OptionT
:
Far more beautiful, concise and readable.
Now if we go a little bit further, we can do the same Either
Either
Future
Either
Either
Either
EitherT
Can be rewritten using EitherT
like this:
I’d say Future[Either[String, Option[User]]
would be a more realistic type to deal with, but it needs its own separate blog post which will also show that Cats or Scalaz are not always the answer to everything and sometimes there are simpler ways to make the code clean and readable.
Conclusion
You don’t need to know about monads and category theory to start using Cats. Types OptionT
EitherT
This doesn’t mean that you should ignore those theory concepts. The rule of thumb for learning abstract concepts is to use metaphors, and you tell me, what metaphor can be better than the real-world use cases of that abstract concept? Note that it's not just about Cats or Scalaz; most of the time, we start with the solutions rather than starting with a firm understanding of the actual problem.