I solved the exercises in a sandbox Scala project that has Cats as a
dependency. The book recommends using a Giter8 template, so that’s what I used:
The above command generates (at the time of writing) a minimal project with the
following build.sbt file:
The above differs a bit from what the book lists, since there are both new Scala
2.13 and Cats versions out already, but I followed along using these settings
with minimal issues.
Exercise 1.3: Printable Library
The definition of the Printable type class can be as follows:
In terms of defining the Printable instances for Scala types, I’d probably
prefer to include those in the companion object of Printable so that they were
readily available in the implicit scope, but the exercise asks us explicitly to
create a PrintableInstances object:
The interface methods in the companion object of Printable can be defined as
follows:
On the above, the print method could have relied on the format method
directly, but I opted to not have the unnecessary call.
For the Cat example, we can define a Printable instance for that data type
directly in its companion object:
This allows us to use the Printable instance without explicit imports:
For the extension methods, we can define the PrintableSyntax object as
follows:
I have opted to use a value class for performance reasons, but for the purpose
of this exercise it was likely unnecessary.
By importing PrintableSyntax._ we can now call print directly on our Cat
instance:
Exercise 1.4.6: Cat Show
To implement the previous example using Show instead of Printable, we need
to define an instance of Show for Cat. Similar to the approach taken before,
we’re defining the instance directly in the companion object of Cat:
Cats implements summoners for the Show type class, so we no longer need to use
implicitly.
This can be used as follows:
Cats doesn’t have an extension method to directly print an instance using its
Show instance, so we’re using println with the value returned by the show
call.
Exercise 1.5.5: Equality, Liberty, and Felinity
A possible Eq instance for Cat can be implemented as follows. Similar to the
above, I’ve opted to include it in the companion object of Cat.