dart-lang / dart-lang/language

Expose interfaces for enums and enum items for generic programming

Open
#1,007 10 comments 7 reactions 0 assignees View on GitHub
request
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

This is the test case I want to satisfy:
```dart
enum TestEnum { anda, murgi }
void main() {
group("EnumConverter should convert to and back between enum and string", () {
// setup
EnumConverter testEnumConverter = EnumConverter();
test("toJson(TestEnum.anda) should return 'anda'", () {
expect(testEnumConverter.toJson(TestEnum.anda), equals("anda"));
});
});
}
```
highlight:
```dart
expect(testEnumConverter.toJson(TestEnum.anda), equals("anda"));
```

I want to write a converter that can take the type of enum and it is impossible to get the enum interface in the type.

In my ideal case scenario, a solution like this should have worked:

```dart
abstract class EnumInterface {
List get values;
}

abstract class EnumItemInterface {
int get index;
String toString();
}

class EnumConverter implements JsonConverter {
@override
T fromJson(String json) {
return (T as EnumInterface)
.values
.firstWhere((element) => element.toString().endsWith(json)) as T;
}

@override
String toJson(T json) {
// just make sure there are no '.' s in the enum class name or this will fail.
return (json as EnumItemInterface).toString().split('.')[1];
}
}
```

Unfortunately, casts like `JSON as EnumItemInterface` are not as mindless in dart and I am met with an error:
```
type 'TestEnum' is not a subtype of type 'EnumItemInterface' in typecast
```

Enums and items in the enums already implement a fixed interface. Just exposing those interfaces in the SDK will give me enough to work with, enabling generic programming with enum classes.

A way to impose interfaces on top of classes that we know have that interface but are cast as not having it would also be cool.

Contributor guide

Open the contributing guide

Research direction

Start with the embedded Dart enum and EnumConverter test case, then read the proposed EnumInterface and EnumItemInterface definitions. Determine whether the SDK or language specification can expose the existing enum interfaces for generic access. Done means an accepted design and corresponding specification or SDK changes that support the demonstrated conversion use case.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.