Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart generic constraints to several types and set default value

I want to make some extension classes for RxDart classes, for convenience. But I couldn't find a way to do some basic thing with generics, e.g. I need to restrict generic type to a couple of types. Here's how I would implement it in C#

MyGenericType<T> where T : bool, int { ... }

thus restricting T to just bool and int types. How would I do the same in dart? The docs only show examples with a single type restriction like this:

class MyGeneric<T extends SomeClass> ...

I tried using comma as well, but it does another thing, it requires my generic type to extend both of them, which is not what I need. Is it possible at all?

And another related question: I also need to set default values for those generics. Again, the C# equivalent would be

T value = default(T);

Is there anything like this in dart?

like image 646
Konstantin Avatar asked Sep 29 '19 04:09

Konstantin


1 Answers

No, and no.

Dart does not have multiple constraints or union types, so you can't have a type variable containing either bool or int, nor a normal variable allowing values of only those types.

Dart types also do not have any way to define default value. Use nullable types and null as the default value instead. All types in Dart are object types and can be made nullable by adding ?.

like image 123
lrn Avatar answered Sep 18 '22 21:09

lrn