Skip to content

Instantly share code, notes, and snippets.

@willeccles
Last active August 26, 2015 22:00
Show Gist options
  • Save willeccles/72eae58916b5f4ef65fc to your computer and use it in GitHub Desktop.
Save willeccles/72eae58916b5f4ef65fc to your computer and use it in GitHub Desktop.
an even better way to pass methods as parameters
public static void main(String[] args) {
// this uses a java 8 feature called method references (i think)
// it looks for method "aThingToDo" in class "methoding" (the name of this class)
// aThingToDo must match the pattern, as doAThing says
doAThing(methoding::aThingToDo);
}
// define a pattern for what type of method we want
// we want a method with String s as input and no return (void)
public interface voidMethod {
// 'run' or whatever you name it will be the method you actually use later on
void run(String s);
}
// this method matches that pattern
public static void aThingToDo(String s) {
System.out.println(s);
}
// this method will run the method we just defined
public static void doAThing(voidMethod v) {
v.run("this will be printed to the console");
}
@willeccles
Copy link
Author

tfw you accidentally save your gist before it's done

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