Why not multiple abstract methods in Functional In

2019-04-28 12:34发布

This question already has an answer here:

@FunctionalInterface
interface MyLambda {
    void apply1();
    int apply2(int x, int y);
}

Now using the Lambda expressions why can't Java allow below two as it clearly differentiate between the two:

MyLambda ml1 = () -> System.out.println("Hello");
MyLambda ml2 = (x, y) -> x+y;

标签: java lambda
3条回答
Evening l夕情丶
2楼-- · 2019-04-28 13:14

Writing Lamba expression meaning we are implementing the interface that is functional interface. It should have one abstract method because at the time of lambda expression, we can provide only one implementation at once. So in the code snippet posted in the question, at any time we are giving only one implementation while declaring Lambda where we will have to implement for two abstract methods.

Thanks for the help.

查看更多
The star\"
3楼-- · 2019-04-28 13:26

The answer would be that in order to create a valid implementation, you would need to be able to pass N lambdas at once and this would introduce a lot of ambiguity and a huge decrease in readability.

The other thing is that @FunctionalInterface is used to denote an interface which can be used as a target for a lambda expression and lambda is a SINGLE function.

Anyway, your example is not valid and would not compile because it tries to create two incomplete implementations on the functional interface.

查看更多
劳资没心,怎么记你
4楼-- · 2019-04-28 13:38

A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract. This "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.

https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8

查看更多
登录 后发表回答