我认为这个问题已经在某个地方,但我找不到它。
我不明白,为什么必须有一个函数式接口(interface)才能使用 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);
}
这可以正常工作,但是如果您取消注释注释行,则不会。为什么?据我了解,编译器应该能够区分这两种方法,因为它们具有不同的输入参数。为什么我需要一个功能接口(interface)并炸毁我的代码?
编辑:链接的重复项没有回答我的问题,因为我在询问不同的方法参数。但是我在这里得到了一些非常有用的答案,感谢所有帮助过的人! :)
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 接口(interface)”提供一个方法。
最佳答案
当你写的时候:
TestInterface i = () -> System.out.println("Hans");
您为 TestInterface
的 void hans()
方法提供一个实现。
如果您可以将 lambda 表达式分配给具有多个抽象方法(即非函数式接口(interface))的接口(interface),则 lambda 表达式只能实现其中一种方法,而其他方法未实现。
您不能通过将具有不同签名的两个 lambda 表达式分配给同一个变量来解决它(就像您不能将两个对象的引用分配给单个变量并期望该变量同时引用两个对象)。
关于java - 为什么我需要一个函数式接口(interface)来使用 lambdas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33010594/