cyclops Java : The Monad Typeclass with Vavr’s Future and Try
We can convert the example code in A type safe, JAVA Monad API. Part I : With Vavr’s Future and Try which uses cyclops’ AnyM Monad API to use cyclops’ more purely functional Typeclass infrastructure.
Rather than return AnyM, we can switch our GenericWork interface to return Higher Kinded encodings instead via the Higher interface from cyclops-react
The Monad Typeclass
The Higher interface is very simple, and unlike AnyM does not provide functional operations such as map or flatMap directly. cyclops-react defines a suite of typeclass interfaces that do provide an API for performing these types of functional operations. To map and flatMap our Higher Kinded Vavr Future and Try objects we will need Instances of the Monad Typeclass for both Future and Try. Luckily these are provided on the Futures and Trys companion classes
Monad<future> monad = Futures.Instances.monad();
Monad<tryType> monad = Trys.Instances.monad();
We can modifiy our Capitalizer class to make use of the Monad Typeclass, as Monad (like other cyclops Typeclasses) does not provide a fluent interface for functional operations, our code is a little more clunky than it was for AnyM.
Higher Kinded encodings for Vavr
cyclops-react types implement the interface Higher, but 3rd party libaries such as Vavr, Functional Java, Reactor or the JDK don’t. We provide higher kinded encodings for third party types by creating Kind instances that implement Higher and store a reference to the raw type.
FutureKind<String> hkFuture = FutureKind.widen(future);
TryKind<Boolean> hkTry = TryKind.widen(myTry);
Higher Kinded Async Work
Higher Kinded Sync Work
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.
And again, the output will look something like this
A fluent-API for working with Typeclasses
cyclops-react has a number of classes that provide a more fluent coder-experience when working with typeclasses and higher-kinded types. Later this week we will publish a solution to the same problem that makes use of the Active Typeclass manager to make this code a cleaner and more fluent.
Further reading
cyclops java : The Active typeclass manager
A type safe, JAVA Monad API. Part I : With Vavr’s Future and Try
Simulating Higher Kinded Types in Java