我认为这个问题已经存在于某处,但我无法找到它。
我不明白为什么需要一个函数式接口来使用 lambda。考虑以下示例:
public class Test {
public static void main(String...args) {
TestInterface i = () -> System.out.println("Hans");
// i = (String a) -> System.out.println(a);
i.hans();
// i.hans("Hello");
}
}
public interface TestInterface {
public void hans();
// public void hans(String a);
}
这可以正常工作,但如果取消注释行,则不会出现问题。为什么?根据我的理解,编译器应该能够区分这两种方法,因为它们具有不同的输入参数。为什么我需要一个函数式接口并破坏我的代码?
编辑:链接的重复项没有回答我的问题,因为我正在询问不同的方法参数。但我在这里得到了一些非常有用的答案,感谢所有提供帮助的人! :)
EDIT2:抱歉,我显然不是母语人士,但准确地说:
public interface TestInterface {
public void hans(); //has no input parameters</br>
public void hans(String a); //has 1 input parameter, type String</br>
public void hans(String a, int b); //has 2 input parameters, 1. type = String, 2. type = int</br>
public void hans(int a, int b); //has also 2 input parameters, but not the same and a different order than `hans(String a, int a);`, so you could distinguish both
}
public class Test {
public static void main(String...args) {
TestInterface i = () -> System.out.println("Hans");
i = (String a) -> System.out.println(a);
i = (String a, int b) -> System.out.println(a + b);
i = (int a, int b) -> System.out.println(a);
i.hans(2, 3); //Which method would be called? Of course the one that would take 2 integer arguments. :)
}
}
我所问的只是关于论点。方法名称并不重要,但每个方法都采用不同参数的唯一顺序,因此,Oracle 可以实现此功能,而不是只为每个“Lambda 接口”提供一个方法。