Home > Software engineering >  Dart generics method not recognizing type
Dart generics method not recognizing type

Time:11-19

I have an abstract base class validator with a method which takes a generic type as parameter. I will be passing generic type parameter to base class from the subclass inheriting the base class.

Base Class:

abstract class BaseValidator {
   bool isValid<T>(T obj);
}

Child Class:

class IPv4Validator extends BaseValidator{

  final IPV4_REGEX = "^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\b){4}\$";

  @override
  bool isValid<String>(String obj) {
    bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj);
    return hasMatch;
  }

}

Here hasMatch takes in non nullable string. When I directly pass some string hasMatch doesn't throw an error. But when I try to pass the generic value in the method parameter, it shows an error.

The argument type 'String' can't be assigned to the parameter type 'String'.

I couldn't able to understand why generic type is not accepting, even though its compile-time type.

enter image description here

CodePudding user response:

The following code solves this particular problem. But it may be different from what you intended to implement. On the other hand, the code will be cleaner if you create a new concrete class for different data types.

abstract class BaseValidator<T> {
  bool isValid(T obj);
}

class IPv4Validator extends BaseValidator<String>{
  final IPV4_REGEX = "^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\b){4}\$";

  @override
  bool isValid(String obj) {
    bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj);

    return hasMatch;
  }
}

CodePudding user response:

another fix that you can do is to use the covariant keyword, to implement that, try this:

abstract class BaseValidator<T> {
  bool isValid(T obj);
}

class IPv4Validator extends BaseValidator {
  final IPV4_REGEX = "^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\b){4}\$";

  @override
  bool isValid(covariant String obj) {
    bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj);
    return hasMatch;
  }
}

CodePudding user response:

can you try with this?

i have run this in dart pad

class IPv4Validator extends BaseValidator{
  final IPV4_REGEX = "^((25[0-5]|(2[0-4]|1d|[1-9]|)d).?\b){4}\$";

  @override
  bool isValid<String>(String obj) {
    bool hasMatch = RegExp(IPV4_REGEX).hasMatch(obj.toString());
    return hasMatch;
  }  
}
  • Related