【发布时间】:2015-10-08 08:34:23
【问题描述】:
我认为这个问题已经在某个地方,但我找不到它。
我不明白,为什么必须有一个函数式接口才能使用 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 接口”提供一个方法。
【问题讨论】:
-
int i = 7; i = 5; System.out.println(i); // wouldn't it be awesome if this would print both 7 and 5? -
我真的不明白你的推理。如果某些东西没有实现接口,那么它怎么可能是那种类型的呢? iPod 不能算作 iPhone,因为你没有碰巧打电话。
-
@immibis:你在这里描述的和我问的不同。 :)
-
@TrudleR 你似乎在问:
<some type> i = <some value>; i = <some other value>; // why can't i be both values at once here?变量i可以持有对 one 对象的引用,不管那是不是由 lambda 表达式创建的对象或您显式编写的类的实例。 -
@TrudleR 所以你想做类似
TestInterface i = new TestInterface() {void hans() {System.out.println("Hans");} void hans(int a) {System.out.println(a);} /* and so on */};的事情?
标签: java lambda java-8 functional-interface