aol / cyclops-integration

Home of the cyclops integration modules : support for Scala, Clojure, RxJava (1+2), Reactor, FunctionalJava, Guava, Dexx & Vavr
http://cyclops-react.io
MIT License
443 stars 51 forks source link

Check and use an option #304

Closed laurent-thiebaud-gisaia closed 6 years ago

laurent-thiebaud-gisaia commented 6 years ago

Hi,

I have an Option that I want to check, throw an exception if its value is null, otherwise use. What is the best way / practice to achieve it? Currently my code is not so beautiful:

myOption.recoverWith(() -> throw new Exception(...)).map(val -> {... return val; }.

I'am looking for something like "orElseThrow" to throw the exception, and a consumer instead of the map.

Thx

johnmcclean commented 6 years ago

Hi @laurent-thiebaud-gisaia,

The API for Option deliberately doesn't have this as an explicit method call (we have a goal of reducing APIs that throw RuntimeExceptions), but you can implement it yourself using fold.


myOption.fold(val->val,
             ()->throw new RuntimeException("..."));