4

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)

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense. Thanks for clarification :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.