I have a Optional
and want to call a function with its' contents if present, and throw if not. The problem is map
will not take a void method.
File file;
//...
Optional maybeFile = Optional.ofNullable(file);
//..
maybeFile
.map(f -> writeTo(f, "stuff")) //Compile error: writeTo() is void
.orElseThrow(() -> new IllegalStateException("File not set"));
How should I implement this while keeping writeTo
void?
orElseThrow
returns the File object if present and so you can write it as
writeTo(maybeFile.orElseThrow(() -> new IllegalStateException("File not set")), "stuff");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With