Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldietrich/e93ff7c282103e3a6406 to your computer and use it in GitHub Desktop.
Save danieldietrich/e93ff7c282103e3a6406 to your computer and use it in GitHub Desktop.
Java Nested Functions
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);
}
}
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);
}
}
interface WouldBeNice {
default String spaces(int count) {
String spaces(String s, int i) {
return (i < 1) ? s : spaces(s + " ", i - 1);
}
return spaces("", count);
}
}
@danieldietrich
Copy link
Author

Why nested functions? Because interfaces do not allow methods other than public visibility.

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