Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of method reference and lambda in Java 8

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)
like image 909
Julian Rubin Avatar asked Dec 15 '22 03:12

Julian Rubin


1 Answers

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.

like image 163
Brian Goetz Avatar answered Feb 28 '23 11:02

Brian Goetz