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:
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
, 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.