Make enhanced enum fields available in constant contexts
In one of my projects, I use enhanced enums to create constants. Some of these should work together with one another. And I have a String field that should have the same value between them. Currently, this must be defined on a private constant and used to instantiate the enum constants.
We can't even write asserts to make sure they match because accessing these fields in a const constructor is invalid.
Since, currently, all enhanced enum fields must be constant, we could think of considering all of them potentially constant (I think that would solve the issue), right? So we could do:
enum One {
a('string a'),
b('bbbbb');
const One(this.value);
final String value;
}
enum Two {
a(.a),
b(.b);
const Two(One one) : value = one.value;
final String value;
}
Is there a better/another solution? Are there any problems with my suggestion? Thanks!
Usual problem: Being an instance variable is not part of the API, only being a getter is.
all enhanced enum fields must be constant
Yes, but they mustn't necessarily be fields. Maybe they aren't in the version that is released tomorrow.
If you can rely on reading a field in a constant expression, but not a getter, then it becomes a breaking change to change a field to a getter. That's undesirable.
To allow that, you'd have to have a way to opt in to the field being usable in constant expressions. That would then make it a breaking change if that's no longer the case.
Usual caveat: We could potentially allow relying on being a field inside the same library, because then you can only break your own code if it changes. It's still a bigger step than just promoting such fields, not sure we'd want to add that complexity.