java - Enums that hold Conditional Logic - Possible? -


to clarify, want this:

message_1042("messagetext", p -> p.contains(message_1032), p -> p.isathing()); 

where later, can call such:

for (message message : messages) {     if (message.conditionsmet()) {         //dothething     } } 

i don't care if can use lambdas, or predicates, or how set conditions, or how they're tested. know own classes, extend class , implement conditionsmet() each individual class.

however, expect have lot of these things, , don't want have package containing hundreds of classes, when have single enum many lines instead.

for more background information: personal project. sort of interactive story i'm working on, , these messages things user can say. however, there can multiple conditions might determine if have option message.

if can store conditions in enum holding text, that's more convenient me. when i'm working enum in other code, won't have worry special conditions. knows own conditions before it's allowed used, , want ask if conditions met.

so there reasonable way obtain in enum? or going have accept having lots of classes?

you can override methods in individual enum items.

enum message {    a() {       @override       public boolean conditionsmet() {           ...       }    },    b() {       @override       public boolean conditionsmet() {           ...       }    },    ...    ;    public abstract boolean conditionsmet(); } 

then given instance of message, calling conditionsmet() pick implementation particular instance.

you can mark enum methods abstract long instances provide implementations.

(thanks dkatzel.)


Comments