In this post we will see how applicatives can be used for validation in Scala. It is an elegant approach. Especially when compared to an object-oriented way.
Usually when we have operations that can fail, we have them return types like
Try. We sequence operations and once there is an error the computation is short circuited and the result is a
None or a
Applicatives allow us to compose independent operations and evaluate each one. Even if an intermediate evaluation fails. This allows us to collect error messages instead of returning only the first error that occurred.
A classic example where this is useful is the validation of user input. We would like to return a list of all invalid inputs rather than aborting the evaluation after the first error.
Scala Cats provides a type that does exactly that. So let's dive into some code and see how it works.