'Enforce providing <T> in Dart generic method
How can I enforce providing the generic type of a generic method in dart. By default, dart allows us to not provide a generic type at all. And this should be a compile time check to be useful.
myMethod<T>(){} // generic method
myMethod<String>(); // this should be valid at compile
myMethod(); // this should be a compile error
One solution comes to mind to write an assertion to check the type of T
. But then it would be a mess to use this check in every method.
Solution 1:[1]
You cannot force people to write a type argument.
It's always allowed to omit the type argument, then type inference will infer one for you. Sometimes it will deduce a specific type from the context or arguments. If not, it will "instantiate to bounds" and use the maximal type allowed. In the case where there is no bound on the type parameter, that's Object?
or dynamic
.
You can disallow that type as argument by giving a bound, like <T extends Object>
. Then that bound is what you'll get if no better type argument is provided or inferred.
At run-time, the code cannot tell the difference between an inferred and an explicit type argument. There is no difference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |