Java8 Lambda函数应用替代语法

Java8 Lambda函数应用替代语法,lambda,java-8,Lambda,Java 8,当使用lambda函数变量时,是否有一种方法可以替代使用apply调用函数 Function<String, String> mesgFunction = (name) -> "Property "+ name +" is not set in the environment"; Optional.ofNullable(System.getProperty("A")).orElseThrow(() -> new IllegalArgumentException(mesg

当使用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=(name)->“属性”+name+“未在环境中设置”;
可选.ofNullable(System.getProperty(“A”)).OrelSetThrow(()->新的IllegalArgumentException(mesgFunction.apply(“A”)));
可选.ofNullable(System.getProperty(“B”)).OrelSetThrow(()->新的IllegalArgumentException(mesgFunction.apply(“B”)));

mesgFunction.apply(“a”)
是否有较短的语法。我尝试了
mesgFunction(“A”)
,抱怨该方法不存在。我错过什么了吗?难道没有更短的选择吗

不,没有这样的选择
apply()
只是
函数
接口的一个方法,所以必须调用该方法。没有语法糖分可以使它更简洁。

不,接口是功能接口这一事实不允许任何替代调用语法;它的方法与任何其他接口方法一样被调用

但是,您可以将更多的常用代码分解出来,以缩短重复的代码

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"));


它的优点是没有代码重复(特别是关于常数
“A”
“B”
),从而减少了意外不一致的空间。

对于lambda来说,这似乎不是一个好的用例。这是你真正想做的吗?为什么不直接把
println
方法中的
->
右边的所有内容都放进去呢?这是有希望的,因为Scala确实做到了这一点。因此,也许在未来的版本中,我们可以在lambdas上获得方法调用的简写版本。为什么不让
函数getRequiredProperty=(name)->可选的.ofNullable(System.getProperty(name)).orelsetrow(()->new IllegalArgumentException(“环境中未设置属性”+name+)?然后调用变成
String valueA=getRequiredProperty.apply(“A”)
。自言自语……说
getRequiredProperty.apply(“A”)
getRequiredProperty(“A”)
有什么好处,通过消除两次指定属性名称的需要,可以减少代码的重复。是的,它比原始代码好,但与普通方法相比仍然没有优势。@JacobvanLingen lambda表达式的主体最终位于所有者类的
private
方法中。当存在具有相同签名的多个函数时,您需要一些猜测或启发式来找到正确的方法,但仍然可以通过反射来调用它。
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");