为什么需要功能接口才能使用Lambda?

我认为这个问题已经存在,但是我找不到。

我不明白,为什么必须要有一个功能接口才能使用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接口”使用一个方法即可。

回答:

当你写:

TestInterface i = () -> System.out.println("Hans");

您可以实现的void hans()方法TestInterface

如果您可以将lambda表达式分配给具有多个抽象方法的接口(即非功能性接口),则lambda表达式只能实现一种方法,而其他方法则无法实现。

您无法通过将两个具有不同签名的lambda表达式分配给同一变量来解决它(就像您不能将两个对象的引用分配给单个变量一样,并且希望该变量一次引用两个对象)。

以上是 为什么需要功能接口才能使用Lambda? 的全部内容, 来源链接: utcz.com/qa/411128.html

回到顶部