简体   繁体   English

可选的 java 8,从方法中“返回”

[英]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 ? processWithParams() 和 process() 两种方法都返回字符串(字符串值是我想从 getErrorMessage() 方法返回的值),这可能吗?

Thank you谢谢

I don't see why you should accept a caller passing null for params .我不明白为什么你应该接受一个为params传递null的调用者。 If anyone calls getErrorMessage with just one argument, param will be an empty array (not null ).如果有人只用一个参数调用getErrorMessageparam将是一个空数组(不是null )。 So I suggest:所以我建议:

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

A caller is not prohibited from calling with null as the second argument.不禁止调用者使用null作为第二个参数进行调用。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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