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 write a type signature for a function that accept class itself, not its object

I’m a newbie in Dart.

I would like to pass a class, NOT a class object, to a function, and it looks like this now:

void passClass(?? Klass) {
  SomeClass obj = Klass();
  ...
}

I don’t what to put to ??.

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

Thanks.

>Solution :

The concept you are looking for is called generics.

void passClass<T>() {
  ...
}

could then be called like this:

passClass<Klass>();

The problem is that you cannot actually make your code work this way, because your code assumes the class that gets passed always has a parameterless constructor. That might be the case for some classes, but not for others.

If you want to create an object of the class you passed, it gets complicated. You can find good solutions at Creating an instance of a generic type in DART

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