Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not multiple abstract methods in Functional Interface in Java8? [duplicate]

Tags:

java

lambda

@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;
like image 578
sairam Avatar asked Aug 02 '17 16:08

sairam


Video Answer


3 Answers

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.

like image 182
Grzegorz Piwowarek Avatar answered Oct 08 '22 17:10

Grzegorz Piwowarek


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.

like image 35
sairam Avatar answered Oct 08 '22 16:10

sairam


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

like image 1
mgyongyosi Avatar answered Oct 08 '22 17:10

mgyongyosi