cyclops java : The Active typeclass manager
In cyclops java : The Monad Typeclass with Vavr’s Future and Try we made use of cyclops’ Monad Typeclass and support for higher kinded types to abstract over synchronous and asynchronous execution modes.
We created a Capitalizer class that was a little clunky. It was clunky because the workload was managed by the Monad typeclass which doesn’t provide a fluent interface.
Luckily cyclops provides another class called Active, which manages the available typeclasses for a type and provides a fluent API into those typeclasses.
Using Active, we can make our Capitalizer code much cleaner (in fact it looks pretty similar to the code for AnyM but we are using the much stricter typeclass infrastructure instead).
We will need to change our AsyncWork and SyncWork implementations to return Active Instances
Switching between Asynchronous and Synchronous execution
Much like before, we can write some test code, to test both our Synchronous and Async implementations. In the first code block we run the Capitalizer asynchronously and in the second synchronously.
To extract the values from the Active instance below we are using a fold (much like the reduce operator on a Java Stream). The boolean parameter false serves as a fallback or default value in case of error, and we Or that with the boolean value stored in the Try or Futures. (Alternatively we could use the same technique as per cyclops Java : The Monad Typeclass with Vavr’s Future and Try and extract the value directly by narrowing the higher kinded Future or Try to it’s raw type.
And again, the output will look something like this
Take this further
cyclops-react has a number of classes for making working with typeclass instances a little more Java friendly. These are
- Active : manage and apply common typeclasses for a single higher kinded type
- Nested : manage and apply common typeclasses for two nested higher kinded types
- coproduct : manage and apply common typeclasses for an Either type for 2 higher kinded types with the same data type (e.g. Either a Future with String result or a Maybe with a String value).
- (in progress) product : a two-valued tuple that manages and applies common typeclasses for 2 higher kinded types with the same data type.
Further Reading
cyclops Java : The Monad Typeclass with Vavr’s Future and Try
A type safe, JAVA Monad API. Part I : With Vavr’s Future and Try
Simulating Higher Kinded Types in Java