-
Notifications
You must be signed in to change notification settings - Fork 135
MaybeT
MaybeT class allow you to manipulate an Optional/s wrapped inside any other monad type (via AnyM). Like AnyM, MaybeT has two sub-types MaybeTValue and MaybeTSeq
MaybeTValue represents an Optional that is nested inside another monad that resolves to a single value (e.g. an Optional / Maybe / Either / Try / Future type).
MaybeTSeq represents an Optional that is nested inside another monad that resolves to a sequence of values (e.g. an Stream or List type).
You can build MaybeT from static creational methods on MaybeT such as fromValue or fromIterable
MaybeTValue<Integer> valueT = MaybeT.fromValue(Maybe.just(Maybe.just(10));
MaybeTSeq<Integer> seqT = MaybeT.fromIterable(Arrays.asList(Maybe.none(),Maybe.just(10));
transformation operation
valueT.map(i->i*2);
//MaybeT[Maybe[Maybe[20]]
flattening transformation
valueT.flatMap(i->Maybe.just(i*2));
//MaybeT[Maybe[Maybe[20]]
A flatMap operator where the transforming function returns another monad transformer
valueT.flatMapT(i->MaybeT.fromOptional(Optional.of(Maybe.just(i*2)));
//MaybeT[Maybe[Maybe[20]]
- MaybeT#unwrap will return the wrapped monad, in general this should only be used locally within the same method that the AnyM is created so we can be sure of it's type.
- MaybeTValue#toXXXX, MaybeTSeq#toXXX there are a large range of conversion operators available on the MaybeTValue and MaybeTSeq types that can convert MaybeT's to JDK or cyclops-react monadic types
- MaybeT#collect JDK 8 collectors can be used to convert an MaybeT from one type to another
- MaybeT#to The to method allows both custom operators and custom converters to be used to convert an MaybeT to another type
AnyM types also have a full range of fold / reduce operators available, which means that data can often be extracted in useful form without conversion back to an unwrapped monadic form.
E.g. to sum all the values in any Sequence type we can write a generic method like so ->
public int sumValues(MaybeT<Integer> sequence){
return sequence.reduce(Monoids.intSum);
}
AnyM extends Publisher so other reactive Streams implementations can subscribe to our AnyM type.
ReactiveSeq<Maybe<Integer>> stream = ReactiveSeq.of(1,2,3).map(Maybe::just);
MaybeTSeq<Integer> seq = MaybeT.fromIterable(stream);
Flux<Integer> flux = Flux.from(seq);
Similarly we can provide a consumer to listen to each event generated by the wrapped monadic type as we iterate over it.
MaybeTValue<Integer> value = MaybeT.fromValue(FutureW.ofResult(Maybe.just(10)));
MaybeTSeq<Integer> seq = MaybeT.fromIterable(ReactiveSeq.of(Maybe.none(),
Maybe.just(10),
Maybe.just(20),
Maybe.just(30)));
value.forEach(System.out::println);
//10
seq.forEach(System.out::println);
//10
//20
/30
oops - my bad