简体   繁体   中英

How does a function from a functional interface perform a lambda function?

I'm trying to understand functional interfaces and lambda functions.And I can't find an explanation of how a function in a functional interface connects it with a lambda function , that is, let's say there is such a functional interface

@FunctionalInterface
interface MyPredicate {
    boolean test(Integer value);
}

and now we assign the variables of the functional interface to the lambda function:

public class Tester {
    public static void main(String[] args) throws Exception {
        MyPredicate myPredicate = x -> x > 0;
        System.out.println(myPredicate.test(10));   //true
    }
}

I'm exactly wondering why when calling myPredicate.test(10) a call is being made x > 0 . That is, do I understand correctly that when we assign a lambda function, the compiler somehow connects the function from the functional interface with the body of the lambda function?it's just that inheritance and override are usually used for this ,but here the compiler does it or how?I will be glad to have explanations to understand this issue

What exactly IS a lambda expression in pre-Java8 terms?

It's an instance of an anonymous class implementing the interface needed in the current context.

So, to understand

MyPredicate myPredicate = x -> x > 0;

we have to consider some different aspects.

Here, the lambda expression x -> x > 0 is required to give a result compatible with MyPredicate . So, by considering the context where the expression is used, it is equivalent to

MyPredicate myPredicate = new MyPredicate() {
    boolean test(Integer whateverName) {
        // some method body
    }
};

Now, the lambda expression fills the body of that method. The x -> part defines the parameter name, so now we have

MyPredicate myPredicate = new MyPredicate() {
    boolean test(Integer x) {
        // some method body
    }
};

And the x > 0 defines the body and the value to be returned:

MyPredicate myPredicate = new MyPredicate() {
    boolean test(Integer x) {
        return x > 0;
    }
};

So, when you call myPredicate.test(10) , there's nothing special going on. The (anonymous-class) instance in myPredicate gets its test() method called with argument 10 . It's only that this instance has been created using the lambda-expression syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM