Java lambda returning a lambda

前端 未结 4 853
借酒劲吻你
借酒劲吻你 2020-11-27 06:01

I am trying to do what seems to be a relatively basic thing in the new JDK 8 land of functional programming, but I can\'t get it to work. I have this working code:

4条回答
  •  無奈伤痛
    2020-11-27 06:22

    Firstly you have to know how compiler get a lambda expression's type. It is achieved by target typing, which means the type of the variable that you assign the lambda expression to. In your case, if you

    Function> fn = n -> () -> { System.out.println(n); return null; }
    

    This is how the lambda get its type: Function>

    Then you have to look at the type inference in generic type: The return type of map is Stream, R would be determined by type of the parameter that you passed into the function. If you map(x->"some string"), then the result is Stream. Now this is the problem, R's type the lambda's type. But lambda needs a target type, which is the variable R.

    The working code works because it explicitly cast the lambda to a type.

提交回复
热议问题