-
Notifications
You must be signed in to change notification settings - Fork 134
X For comprehensions
John McClean edited this page Jul 5, 2018
·
4 revisions
For comprehensions are a handy short cut for combining nested flatMap operations. For example we can sequence nested calls to methods that return a type that supports flatMap such as Option, Try, Stream, IO and flatten out the result to a single Option, Try, Stream or IO.
E.g. imagine a car parking system that attaches a monthly membership fee to each user (depending on selected grade) and potential costs per use to each of the users registered cars (again depending on grade). A typical business class may have methods something like this
public Option<User> load(long id);
public Option<List<Car>> extractCarDetails(User user);
public Option<BigDecimal> totalBalance(User user,List<Car> cars);Chaining calls together to calculate a users total outstanding balance would involve messy nested flatMaps.
Option<BigDecimal> balance = load(100L).flatMap(user->extractCarDetails(user)
.flatMap(cars->totalBalance(user,cars));
This can be rewritten, in a cleaner form using for comprehensions
Option<BigDecimal> balance = load(100L).forEach2(this::extractCarDetails,this::totalBalance);oops - my bad