Skip to content

Instantly share code, notes, and snippets.

@pbkwee
Created March 10, 2022 00:59
Show Gist options
  • Save pbkwee/78505c78a635b3d682100780db294cfd to your computer and use it in GitHub Desktop.
Save pbkwee/78505c78a635b3d682100780db294cfd to your computer and use it in GitHub Desktop.
Using a Consumer pattern vs. a constructor to populate an Enum instance. Handy if you
have a good number of fields and don't want long argument lists. Or if you need to do
some processing/method calling.
final fields would cause issues and would need to be done via a constructor without a callback.
public enum SomeEnum {
A((c)->{c.someField="A";}),
B((c)->{c.lotsMoreFields="B";}),
/*Syntax error
C(null) {
this.someField="a";
}*/
;
SomeEnum(Consumer<SomeEnum> c) {
c.accept(this);
}
String someField;
String lotsMoreFields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment