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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great! Wrote an article about that.