Created
May 14, 2017 11:24
-
-
Save stevenschwenke/b3619c71bfaa0df93754dcec49aa89a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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.
Great! Wrote an article about that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@schauder Das hier meine ich