I'm wondering why methods references and lambdas are not recognized as a Function. Why I need to write
Function<Integer, Integer> fun1 = i -> i+2;
Function<Integer, Integer> fun2 = i -> i*i;
fun1.compose(fun2).apply(4);
instead of
((Integer i) -> i*2).compose((Integer i) -> i+2).apply(4)
Lambda expressions have no intrinsic type; the following is an error:
Object lambda = x -> x;
Lambda expressions are poly expressions, which are expressions whose type is dependent on their context.  In particular, a lambda expression derives its type from its target type, which must be a functional interface -- an interface with a single (non-Object) abstract method.  The same lambda expression could have multiple types, depending on its target type:
Predicate<String> isEmpty = s -> s.isEmpty();
Function<String, Boolean> isEmpty = s -> s.isEmpty();
The interface Function is not part of the language, nor does it have any magic properties; it is merely an ordinary functional interface, just like Runnable or Predicate or Comparable.  There's no reason the compiler could guess that you meant the lambda to target Function rather than some other type.
Further, you don't need to be a lambda to implement Function; you could be a named class or an anonymous class.  Lambdas (and method refs) are a syntactically compact means of specifying instances of functional interfaces.  
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With