Skip to content
johnmcclean-aol edited this page Nov 22, 2016 · 9 revisions

Overview

AnyM is a special type of functor in cyclops-react. It is a functor that abstracts over monads (and has two monadic sub-types AnyMValue and AnyMSeq). That is, it is an interface that can wrap any monad type. This allows us to write common code that can accept an Optional, CompletableFuture, Stream or List from the JDK as well as any of the cyclops-react datatypes (extended collections, LazyFutureStreams, FutureW, Try, Xor, Ior, FeatureToggle, Reader or Maybe). Via the cyclops integration modules we can also abstract over types from Javaslang, Functional Java, RxJava, Reactor and Guava.

Values and sequences

We split the AnyM type into 2 sub-types AnyMValue and AnyMSeq. AnyMValue represents any monad that ultimately resolve to a single value (such as Maybe / Optional / Either / Try / Future / Reader) and AnyMSeq represents any monad that ultimately resolves to a sequence of values.

AnyM itself is not a monad, we can't safely represent the flatMap method on it, but it's two sub-types are. Both AnyMValue and AnyMSeq implement flatMap.

Value Example

Use AnyM to combine Optionality (Optional) and Exception handling (Try). AnyM can be used to augment functionality missing from the original implementation (for example Applicative like combining in java.util.Optional or monadic flatMapping in guava's Optional).

AnyMValue tryMonad = AnyM.fromTry(Try.success(20)); AnyMValue optMonad = AnyM.fromOptional(Optional.of(10));

  1. using flatMap (monad methods)
intMonad.flatMap(i->tryMonad.map(s->s+i))
        .map(i->i*2);

//AnyMValue[60]
  1. using combine (Applicative Functor methods)
intMonad.combine(tryMonad,s->(s+i)*2);
       
//AnyMValue[60]

Class diagram

class hierarchy

Clone this wiki locally