Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stevenschwenke/b3619c71bfaa0df93754dcec49aa89a4 to your computer and use it in GitHub Desktop.
Save stevenschwenke/b3619c71bfaa0df93754dcec49aa89a4 to your computer and use it in GitHub Desktop.
private int methodWithoutParameter() {
return 0;
}
/**
* Equals exactly method signature of java.util.function.Function:apply
*/
private int methodWithParameter(int x) {
return x;
}
@Test
public void blubber() {
Map<Integer, Integer> myMap = new HashMap<>();
// Both lambda and method reference can be used to implement Function, if the method signature equals
// signature of java.util.function.Function::apply:
Function<Integer, Integer> functionWithParameter1 = (k) -> methodWithParameter(k);
Function<Integer, Integer> functionWithParameter2 = this::methodWithParameter;
myMap.computeIfAbsent(2, functionWithParameter1);
myMap.computeIfAbsent(2, functionWithParameter2);
functionWithParameter1.apply(5);
// Only lambda can be used to implement Function if the method signature differs from the right signature:
Function<Integer, Integer> functionWithoutParameter1 = k -> methodWithoutParameter();
Function<Integer, Integer> functionWithoutParameter2 = this::methodWithoutParameter; // not possible
myMap.computeIfAbsent(2, functionWithoutParameter1);
functionWithoutParameter1.apply(5);
}
@stevenschwenke
Copy link
Author

@schauder Das hier meine ich

@schauder
Copy link

The types don't match. A method without parameter returning an int is a Supplier<Integer>. A lambda taking an int argument, ignoring it and returning an int is still a Function<Integer, Integer.

If you want a lambda equivalent to a method reference of a method without parameter you would want

() -> methodWithoutParameter()

And you wouldn't be able to assign that to a Function<Integer, Integer> either.

@stevenschwenke
Copy link
Author

Great! Wrote an article about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment