What is meant by lambda target type and target type context in Java?

后端 未结 2 1566
遥遥无期
遥遥无期 2021-02-15 10:00

I\'m reading a chapter on lambdas in Herbert Schildt\'s \"Java: The Complete Reference\" and there are quite a few references to \"lambda target type\" and \"target type context

相关标签:
2条回答
  • 2021-02-15 10:13

    You should understand "target type" as the functional interface as which the function is (intended to be) used.

    Think about this: what is this lambda expression expected to be and how can it be used?

    () -> "123";
    

    As the book notes it, this expression can't be used on its own. It needs to be associated with a functional interface.

    Now, what functional interface can be the type of a lambda expression is picked up from the context. This is where the "target type" of the lambda expression means something.

    Consider these examples:

    Example 1:

    void printString(Supplier<String> supplier) {
        System.out.println(supplier.get());
    }
    

    You can call that with

    printString(() -> "123");
    

    In this case, you mean the type of () -> "123" to be Supplier<String>. That's the target type of () -> "123" in this context.

    Example 2:

    MyInterface<String> myInt = () -> "123";
    

    As you can see, an identical lambda expression was used, but its target type is now MyInterface<String>.

    Likewise, you can declare another functional interface that has the same signature as MyInterface.func() and assign the very same lambda expression to it. The target type changes in these varied contexts.

    0 讨论(0)
  • 2021-02-15 10:19

    One of the definitions of "target" (taken from here) is:

    a result or situation that you intend to achieve.

    You can say the result a lambda expression intends to achieve is to implement some functional interface. Hence that functional interface can be seen as the target of that lambda expression, and the type of the functional interface is the target type.

    Hence the target type is the type of the functional interface implemented by the lambda expression.

    The target type can be inferred based on the context in which the lambda expression is used:

    1. If the lambda expression is assigned to a functional interface reference variable, the type of that variable is the target type.
    2. If the lambda expression is returned by some method, the return type of the method is the target type.
    3. If the lambda expression is passed as an argument to a method, the type of the corresponding argument expected by the method is the target type.

    In

    (int n) -> n % 2 == 0
    

    the target type is unknown. If you assign this expression to some functional interface reference, that would be the target type.

    In

    MyInterface<String> myInt = () -> { return "123"; }
    

    the target type is MyInterface<String>.

    0 讨论(0)
提交回复
热议问题