简体   繁体   中英

Optional java 8 with "return" from methods

Ok I would like to create a method that returns a String depending on some condition (whether the parameter is null or not) :

private static String getErrorMessage(String code, Object... params) {
    Optional.ofNullable(params)
              .ifPresent(params -> processWithParams(code,params))
              .orElse(() -> process(code));
}

Both methods processWithParams() and process() return String (the string value is the value I want to return from getErrorMessage() method), is it possible ?

Thank you

I don't see why you should accept a caller passing null for params . If anyone calls getErrorMessage with just one argument, param will be an empty array (not null ). So I suggest:

    Objects.requireNonNull(params);
    return processWithParams(code, params);

A caller is not prohibited from calling with null as the second argument. If your code already has many such calls and you don't want to clean that up just now:

    if (params == null) {
        params = new Object[] {};
    }
    return processWithParams(code, params);

However, if for some strange reason you insist, Boris the Spider is correct:

    return Optional.ofNullable(params)
              .map(p -> processWithParams(code, p))
              .orElse(process(code));

Or if processing for no need is prohibitively expensive:

              .orElseGet(() -> process(code));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM