Last active
August 29, 2015 14:04
-
-
Save danieldietrich/e93ff7c282103e3a6406 to your computer and use it in GitHub Desktop.
Java Nested Functions
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
interface NestedFunWithLambda { | |
default String spaces(int count) { | |
final BiFunction<String, Integer, String> spaces = | |
// compiler complains that spaces may not have been initialized | |
(s, i) -> (i < 1) ? s : spaces.apply(s + " ", i - 1); | |
return spaces.apply("", count); | |
} | |
} |
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
interface NestedFunWithLocalClass { | |
default String spaces(int count) { | |
final class Spaces { | |
String apply(String s, int i) { | |
return (i < 1) ? s : this.apply(s + " ", i - 1); | |
} | |
} | |
return new Spaces().apply("", count); | |
} | |
} |
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
interface WouldBeNice { | |
default String spaces(int count) { | |
String spaces(String s, int i) { | |
return (i < 1) ? s : spaces(s + " ", i - 1); | |
} | |
return spaces("", count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why nested functions? Because interfaces do not allow methods other than public visibility.