当使用lambda函数变量时,有没有用apply调用函数的替代方法?
Function<String, String> mesgFunction = (name) -> "Property "+ name +" is not set in the environment";
Optional.ofNullable(System.getProperty("A")).orElseThrow(() -> new IllegalArgumentException(mesgFunction.apply("A")));
Optional.ofNullable(System.getProperty("B")).orElseThrow(() -> new IllegalArgumentException(mesgFunction.apply("B")));mesgFunction.apply("A")有没有更短的语法?我试过mesgFunction("A"),它抱怨这个方法不存在。我是不是遗漏了什么?有没有更短的替代方案?
发布于 2016-09-21 20:21:15
不,接口是函数接口这一事实不允许任何替代的调用语法;它的方法像任何其他接口方法一样被调用。
但是,您可以只提取更多的公共代码,以缩短重复的代码
Function<String, Supplier<IllegalArgumentException>> f = name ->
() -> new IllegalArgumentException("Property "+name+" is not set in the environment");
String valueA = Optional.of("A").map(System::getProperty).orElseThrow(f.apply("A"));
String valueB = Optional.of("B").map(System::getProperty).orElseThrow(f.apply("B"));然而,这仍然没有比传统的
public static String getRequiredProperty(String name) {
String value = System.getProperty(name);
if (value == null) {
throw new IllegalArgumentException("Property "+name+" is not set in the environment");
}
return value;
}String valueA = getRequiredProperty("A");
String valueB = getRequiredProperty("B");其具有没有代码重复的优点(特别是,关于常量"A"和"B"),因此意外不一致的空间较小。
发布于 2016-09-21 05:22:35
不,没有这样的选择。apply()“仅仅”是Function接口的一个方法,所以必须调用该方法。没有语法糖可以让它变得更简洁。
https://stackoverflow.com/questions/39603806
复制相似问题