-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How could I pass something like Enum.Type
as function parameter in dart lang?
#53771
Comments
enum Foo { a }
enum Bar { b }
/// define
void anyFunction<T extends Enum>(List<T> values, String enumStringValue) {
var value = values.byName(enumStringValue);
print('greet, I got a $value');
}
/// calling
void main() {
anyFunction(Foo.values, 'a'); // greet, I got a Foo.a
anyFunction(Bar.values, 'b'); // greet, I got a Bar.b
anyFunction(Foo.values, 'b'); // throw
} |
Thank you for your inspiration! |
@ykmnkmi's solution is quite nice, because it avoids relying on objects of type It is normally not recommended to use objects of type Nevertheless, in this particular case we're dealing with enumerated types, and they are special in that they never have any subtypes (other than bottom types like So let's try to use enum Foo { a }
enum Bar { b }
const enumValues = <Type, List<Enum>>{
Foo: Foo.values,
Bar: Bar.values,
};
T anyFunction<T extends Enum>(String enumStringValue) =>
enumValues[T]!.byName(enumStringValue) as T;
void main() {
Foo foo = anyFunction("a"); // OK.
Bar bar = anyFunction("b"); // OK.
Foo badFoo = anyFunction("b"); // Throws.
} The crucial trade-off is that you need to have a "registry" (here we're using I'll close this issue because it doesn't report on anything that doesn't work as intended. |
Static interfaces would make this much simpler in Dart. |
Static interfaces: Probably similar to some proposals in dart-lang/language#356. That would indeed give us a mapping like However, we should keep in mind that some applications are large, and size matters. It is an undecidable property of a program (in Dart and in many other languages) exactly which values any given type parameter will have at run time, and this means that we might ask the language to store a huge map like |
What I want in short:
I'm trying to sync enum between different flutter engines but I found it is hard for me to create an
Enum
by string. I must write different method for different enum which is a little "ugly".By the way, could I pass something like
Class.Type
?The text was updated successfully, but these errors were encountered: