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?
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 ?
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With