Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart: Check Type T of generic function

I have a generic function. I’m trying to return a value based on the type T,
however, my function never seems to match any types (see code below):

int _getCollection<T>() {
    print(T); // the actual type
    print(T is ClockData); // ClockData is a class I created

    // always returns false when passing _getCollection<ClockData>()
    if (T is ClockData) { 
      return 1;
    } else if (T is UserData) {
      return 2;
    } else {
      throw Exception();
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is operator will check if left operand is an instance of right operand. T is a type parameter and not an instance of ClockData. You can use == operator to compare those:

int _getCollection<T>() {
  if (T == ClockData) { 
    return 1;
  } else if (T == UserData) {
    return 2;
  } else {
    throw Exception();
  }
}

Please not this checks for identity and will not support subtypes. If you need to support type inheritance (passing subclasses of ClockData as T) you can use a trick like this:

int _getCollection<T>() {
  if (<T>[] is List<ClockData>) {
    return 1;
  } else if (<T>[] is List<UserData>) {
    return 2;
  } else {
    throw Exception();
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading