xsahil03x / super_enum

Create super-powered dart enums similar to sealed classes in Kotlin
https://pub.dev/packages/super_enum
MIT License
116 stars 13 forks source link

Generics support? #18

Closed bizz84 closed 4 years ago

bizz84 commented 4 years ago

This is more of a question than anything else.

It would be really cool if we could define generic types like so:

@superEnum
enum _Result<T> {
  @object
  NotLoaded,

  @object
  Loading,

  @object
  Error,

  @Data(fields: [
    DataField('data', T),
  ])
  Loaded,
}

This would be extremely useful as we could use the same _Result type to handle multiple model classes.

However I assume this can't be done as Dart doesn't support enums with generics?

Would this be achievable by using standard classes?

Great library btw!

xsahil03x commented 4 years ago

Yes, Initially Generic sealed classes were our actual use-case. But as we know Dart doesn't support enums with generics, So instead of specifying it in the enum, we started specifying it in the DataField.

A simple example would be something like this :

@superEnum
enum _Result {
  @object
  NotLoaded,

  @object
  Loading,

  @object
  Error,

  @generic
  @Data(fields: [
    DataField('data', Generic),
  ])
  Loaded,
}

Try it and let us know if this works for you or not ?

xsahil03x commented 4 years ago

Also, these are the basic rules that we defined for super_enum

@Data() marks an enum value to be treated as a Data class.

- One should supply a list of possible fields inside the annotation.

- If you don't want to add fields, use @object annotation instead.

- Fields are supplied in the form of DataField objects.

- Each DataField must contain the name and the type of the field.

- If the field type needs to be generic use Generic type and annotate the enum value with @generic annotation.

@object marks an enum value to be treated as an object.
bizz84 commented 4 years ago

Ah yes, I missed the bit about Generic.

Thank you for the clarification :)