Vavr’s flatMap in action

Otherwise we could end up with an exception being thrown, if the Try would wrap a failure and there would go our “don’t throw, return a Try” professional programming style.This can be fixed with flatMap:flatMap will either return a success wrapping a String or one of the two possible failures: an exception from wrapThrowOnXYZ() or an exception from anotherTryWrapper().To sum it up: flatMap on a Try of Tries returns a Try.Success if all the Tries are successful or the first Try.Failure encountered in the chain.5) flatMap that Option of OptionThe next example shows a very similar approach, just with Options.Once you’re methods return Options wrapping a value or an Option.None, you’ll encounter this situation: from within an Option context you provide a mapper returning also an Option:Again we’re left with 3 possible results:- the outer Option is a None,- the outer Option is a Some, but the inner Option is a None,- the outer Option is a Some and the inner Option is a Some.We cannot call get() on the outer Option to unpack the inner Option, without calling isDefined() first. Otherwise an exception is thrown if the Option is a None. What we want is just one Option being either None or Some. And here flatMap shines again.To sum it up: flatMap applied on an Option of another Option results in an Option.Some if all Options are Some or an Option.None otherwise.6) flatMap that Either of EitherAs stated earlier, map applies a mapping function on a success..In case of an Either, this is the Right value..Having said that, let’s see how to apply flatMap on an Either.The outerEither Either is – an Either.Right wrapping the age String, if age is not null,- an Either.Left wrapping “empty” if age is null.Applying flatMap returns- an Either.Left wrapping “empty” if outerEither is Either.Left,- an Either.Left wrapping a String that could not be parsed to an Integer,- an Either.Right wrapping an Integer if age could be parsed successfully.To sum it up: flatMap on an Either of another Either results in an Either.Right if all Eithers are Right or an Either.Left wrapping the first Left encountered.All the examples are available on GitHub and there is also a test suite provided to play around with different inputs.To finally sum it up: there are many ways flatMap can be used to process data..However now it should be clear what it means to map a List element, a Try.Success, an Option.Some,a completed Future or an Either.Right and then flatten the result.. More details

Leave a Reply