Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 方法参考↔;λ等价_Java_Intellij Idea_Method Reference - Fatal编程技术网

Java 方法参考↔;λ等价

Java 方法参考↔;λ等价,java,intellij-idea,method-reference,Java,Intellij Idea,Method Reference,如果将光标放在IntelliJ IDEA中的绑定接收器方法引用上,如str::toUpperCase,然后按Alt+Enter,它会将其替换为lambda。如果继续,它会将方法引用更改为()->str.toUpperCase()。这可能是IntelliJ IDEA中的一个bug,尽管我怀疑这也是其他IDE中的一个常见bug。为什么?嗯,这并不总是等价的。以下面的小谜题为例。以下代码的输出是什么 import java.util.function.Supplier; public class S

如果将光标放在IntelliJ IDEA中的绑定接收器方法引用上,如
str::toUpperCase
,然后按Alt+Enter,它会将其替换为lambda。如果继续,它会将方法引用更改为
()->str.toUpperCase()
。这可能是IntelliJ IDEA中的一个bug,尽管我怀疑这也是其他IDE中的一个常见bug。为什么?嗯,这并不总是等价的。以下面的小谜题为例。以下代码的输出是什么

import java.util.function.Supplier;

public class Scratch {

    private static String str;

    public static void main(String[] args) {
        str = "a";
        Supplier<String> methodref = str::toUpperCase;
        Supplier<String> lambda = () -> str.toUpperCase();

        str = "b";
        System.out.println(methref.get());
        System.out.println(lambda.get());
    }
}
导入java.util.function.Supplier;
公共课刮刮{
私有静态字符串str;
公共静态void main(字符串[]args){
str=“a”;
供应商methodref=str::toUpperCase;
供应商lambda=()->str.toUpperCase();
str=“b”;
System.out.println(methref.get());
System.out.println(lambda.get());
}
}

这段代码表明方法引用和lambda是不等价的。代码在每行上打印不同的值:“a”和“b”。我的问题是:这种方法参考的正确lambda等效物是什么?

对于您的供应商设置,答案是:没有等效物

当你写作时:

str = "a";
Supplier<String> methodref = str::toUpperCase;
str=“a”;
供应商methodref=str::toUpperCase;

它字面上变成了
“a”::toUpperCase
(实际编译)。

关于IntelliJ bug,它只是应该像以另一种方式执行时那样指示“(可能会改变语义)”。你应该报告。