Before we start talking about the Functional Programming with the Scala Cats, we should refresh our memory about the Type Class and Implicit. These are the base when we start learning the Scala Cats.
Let’s start the discussion with the Type Class.
A type class is an interface or API that represents some functionality, which we want to implement. Type class is programming pattern in Haskell which allows us to extend existing libraries with new functionality. In Cats, a type class is represented by a trait with at least one type parameter.(If you don’t know about the trait or want to refresh look here: Back2Basics: The Story of Trait – Part 1)
Now we will see, how can we implement Type Class with traits:
Here as we can see that JsonWriter is a Type class with the Json which provides the support for the rest operations.
Now we will discuss the Type Class Instances because it provides the implementation for the types. Now in Scala, we create the instance with the help of concrete implementation and implicit. Example:
Now we will create a Type Class Interface, which will expose the functionality to the users. Interface use the generic method that will take the instance of the type class as an implicit parameter. We can access interface in two way:
- Interface Object
- Interface Syntax
Interface Object: Now we can create an interface. It will place a method into a singleton object:
Now we can call it like this:
Here we can see that we haven’t provided the implicit parameter but we are calling the toJson method. Now compiler will search for the type class instance and provide it to the call like:
Interface Syntax: We can use extension methods also for extending the existing type with the interface.
Now we can use it, like this:
Again we can see that we haven’t provided the implicit parameter but we are calling the toJson method. Now compiler will search for the type class instance and provide it to the call like:
So we have discussed till now for the Type Class. In our next blog, we will talk about the Implicit and Scala Cat Structure.