Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: extends generic class with restrictions

Is this the correct way to declare a "generic class" that extends another "generic class" in dart? Note that the generic parameter has a type restriction.

// available types
class BaseType {}
class DerivedType extends BaseType {}

class BaseClass<Type extends BaseType> {
  final Type prop;
  BaseClass(this.prop) {
    // can be either BaseType or DerivedType
    print(prop);
  }
}

class DerivedClass<Type extends BaseType> extends BaseClass<BaseType> {
  DerivedClass(BaseType prop) : super(prop);
}

The above code works, but I'm not sure if I am using the correct syntax.

like image 751
Cequiel Avatar asked Jun 14 '16 20:06

Cequiel


People also ask

Can a generic class be extended?

We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic.

What is generic class in Dart?

Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language. By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types.

What is type T in Dart?

T is the generic data type eg String, int or CustomModel etc. f is the function E is the new element returned by the function.


1 Answers

Although your code is correct I think you made a semantic mistake in the generic of DerivedClass:

// available types
class BaseType {}
class DerivedType extends BaseType {}

class BaseClass<T extends BaseType> {
  final T prop;
  BaseClass(this.prop) {
    // can be either BaseType or DerivedType
    print(prop);
  }
}

class DerivedClass<T extends BaseType> extends BaseClass<T /*not BaseType*/> {
  DerivedClass(T /*not BaseType*/ prop) : super(prop);
}
like image 136
Alexandre Ardhuin Avatar answered Sep 19 '22 01:09

Alexandre Ardhuin