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

后端 未结 3 1934
臣服心动
臣服心动 2021-02-15 09:23

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

3条回答
  •  我在风中等你
    2021-02-15 10:26

    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 myInt = () -> { return "123"; }
    

    the target type is MyInterface.

提交回复
热议问题