Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart, constraints on Generics?

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{  } 
like image 714
Daniel Robinson Avatar asked Sep 09 '13 13:09

Daniel Robinson


People also ask

What are the constraints in generics?

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.

Can generic classes be constrained?

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.

How do you use generics in Dart?

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.

What are the advantages of using generics?

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.


1 Answers

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 an extends clause that specifies the upper bound for T. If no extends clause is present, the upper bound is Object. 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.

like image 195
Alexandre Ardhuin Avatar answered Oct 02 '22 07:10

Alexandre Ardhuin