I am implementing some dynamic input validator in Dart. See code:
abstract class Validator<T> {
void validate(T value);
static Validator<T> create<T>(String validatorType) {
if (validatorType == 'name') {
return NameValidator<T>();
}
if (validatorType == 'range') {
// How to write: assert(T is Comparable)
return RangeValidator<T>(); // error: 'T' doesn't extend 'Comparable<dynamic>'.
}
return null;
}
}
class NameValidator<T> extends Validator<T> {
@override
void validate(T value) {
assert(value.toString() == "foo");
}
}
class RangeValidator<T extends Comparable> extends Validator<T> {
@override
void validate(T value) {
assert(value.compareTo(42) < 0);
}
}
The static function of the base class Validator.create()
will create an instance of subclass based on the given validatorType
. The generic paramater T
in subclass RangeValidator
class needs to be comparable, but it is not a requirement in base class Validator
and subclass NameValidator
.
I have two questions:
- How to write code the validate the generic type
T
extendsComparable
? - How to cast type
T
toComparable
to instantiate the subclassRangeValidator
?
Thanks.