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

How to test if dynamic variable is generic type void in Dart

I have a scenario in dart where I have a generic type T, which may be <void> at runtime. I need to test if a dynamic variable I get back from a service is of that generic type.

However the following test using the is operator fails when T is void, and I’m struggling to understand why. Can anyone explain this, and suggest a way I can test for this?

void main() {
  test<void>();
}

void test<T>() {
    dynamic foo = 42;
    print('$foo is void: ${foo is T}');
}

42 is void: true

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

>Solution :

In Dart, the is operator checks whether a given object is an instance of a specific type, or a subtype of that type. However, since void is a special type in Dart, it cannot be used as a type parameter for a generic class or function. This means that the type T cannot be replaced with void at runtime.

If you want to test whether a dynamic variable is of a generic type, you can use the Type class instead. Here’s an example:

void main() {
  test<void>();
}

void test<T>() {
    dynamic foo = 42;
    print('$foo is of type $T: ${foo.runtimeType == T}');
}

In this code, I’m using runtimeType to get the runtime type of the foo variable, and comparing it to the type T using the == operator. This will return true if the runtime type of foo is the same as T, and false otherwise. Note that this approach will work with any type, including void.

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