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 to initialize generic fields #973
Comments
It should work to pass the builder to a generic method:
it would make sense to have Thanks. |
I have to add type cast because analyzer is complaining about it. static void _initializeBuilder(FooBuilder b) => _initializeBuilderGeneric(b);
static void _initializeBuilderGeneric<T>(FooBuilder<T> builder) {
if (T == int) {
builder
..field1 = (-1) as T?
..field2 = (-1) as T?;
}
} |
This doesn't seem to work. static void _initializeBuilder(FooBuilder b) => _initializeBuilderGeneric(b);
static void _initializeBuilderGeneric<T>(FooBuilder<T> builder) {
builder
..field1 = ListBuilder<T>();
} I get this:
|
The first example does not work either. |
Sorry, yes, that doesn't work. You'll need to use 'is', like this
actually it looks like it does work to get the generic type parameter, although I did not design this :) e.g.
you still to use I'll add some test coverage for this. |
Since type parameter cannot be accessed from
static void _initializeBuilder
method, it is not possible to initialize generic fields. Is there any workaround? I want to initialize based on all possible types of the generic. For example if T is int, initial value will be 0, if T is String, it will be ''.The text was updated successfully, but these errors were encountered: