Is there a Dart equivalent syntax to the c# ability to specify type constraints on a generic type, e.g. in C#-like syntax where TBase is SomeType
:
class StackPanel<TBase> extends Panel<TBase> where TBase : SomeType{ }
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.
The use of Generics makes the use of a single compulsory data type to be held inside the collection. Such collections are called type-safe collections. By the use of generics, type safety is ensured in the Dart language. We can use List, Set, Map, and Queue generics to implement type safety in Dart.
Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.
You can specify type constraints like this :
class StackPanel<TBase extends SomeType> extends Panel<TBase> { }
The language specification says :
A type parameter
T
may be suffixed with anextends
clause that specifies the upper bound forT
. If no extends clause is present, the upper bound isObject
. It is a static type warning if a type parameter is a supertype of its upper bound. The bounds of type variables are a form of type annotation and have no effect on execution in production mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With