Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 interface default method return type not clear

recently i started reading about java8 features,and one such feature i came across was

default method

,there is nothing unique as far as concept is concerned,but i stumbled across this code snippet which used lambda expression for returning the value(void) from the default method.but i see that the return type of the default method is of the type interface.(which i believe should be void),since the logic inside the default method doesn't return anything ,Now i am puzzled by the behavior as i don't see any compilation error,But when i set the type of the default method as void ,the compiler spouts(The target type of this expression must be a functional interface) error. Could someone explain about this behavior wrt to the lambda usage.

public interface Op {
void runOp();
static void timeOperation(Op testOp) {

}

 default Op combinedOp(Op secondOperation) {
    return ()->{secondOperation.runOp();};
}
}
like image 553
Sal Avatar asked Sep 14 '25 15:09

Sal


2 Answers

You can always write a lambda expression in a non-lambda way with an anonymous class containing the implementation of the single abstract method.

Applied to your example, you can write the method

default Op combinedOp(Op secondOperation) {
    return ()->{secondOperation.runOp();};
}

in a non-lambda way like this:

default Op combinedOp(Op secondOperation) {
    return new Op() {
        @Override
        public void runOp() {
            secondOperation.runOp();
        }
    };
}

Now it is clearer to see that the combinedOp method returns something, i.e. an instance of the Op interface.

However, the runOp method of this instance returns nothing. Hence its return type is void.

like image 172
Thomas Fritsch Avatar answered Sep 16 '25 06:09

Thomas Fritsch


Op is a functional interface i.e. an interface with a SAM (single abstract method).

The combinedOp is a default method which takes an Op as a parameter and returns an Op not void. In Java, functional interfaces can be used as target types for lambda expressions or method references hence the code below is completely valid:

default Op combinedOp(Op secondOperation) {
    return ()->{secondOperation.runOp();};
}

this code consumes an Op which then returns a function which when called upon will execute the secondOperation function.

like image 30
Ousmane D. Avatar answered Sep 16 '25 05:09

Ousmane D.