I want to be able to construct an object from inside a generic function. I tried the following:
abstract class Interface
{
Interface.func(int x);
}
class Test implements Interface
{
Test.func(int x){}
}
T make<T extends Interface>(int x)
{
// the next line doesn't work
return T.func(x);
}
However, this doesn't work. And I get the following error message: The method 'func' isn't defined for the class 'Type'
.
Note: I cannot use mirrors because I'm using dart with flutter.
A variation of Günter Zöchbauer's excellent answer and using the new constructor tearoff feature in Dart 2.15 could be to add an extra parameter to the generic function to provide the constructor (using Test.new
for a default constructor, if required).
T make2<T extends Interface>(int x, T Function(int) constructor)
{
return constructor(x);
}
make2<Test>(5, Test.func);
// Default constructor
make2<Test>(5, Test.new);
The T Function(int) constructor
parameter is a Function which takes an int
argument and returns Type T
.
You could have done this without constructor tear-offs too, but (for me at least) this is just a little too much to parse.
make2<Test>(5, (int x) => Test.func(x));
This also has the useful attribute that if a developer copies and pastes the function without changing the parameter, they should be alerted by static analysis (since AnotherTest.func
doesn't return Test
), rather than only finding out at runtime when the factory list is compared to the types.
// ERROR: The argument type 'AnotherTest Function(int)' can't be
// assigned to the parameter type 'Test Function(int)'
make2<Test>(5, AnotherTest.func);