Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way of mapping across Optional with void method

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?

like image 930
Ken Avatar asked Dec 18 '22 21:12

Ken


1 Answers

orElseThrow returns the File object if present and so you can write it as

writeTo(maybeFile.orElseThrow(() -> new IllegalStateException("File not set")), "stuff");
like image 99
user7 Avatar answered May 10 '23 19:05

user7