dart-lang / dart-lang/language
Sum/union types
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
[Edit by eernstg: I removed 'type matching' from the title because Dart has pattern matching today.]
I'd like to import some features from functional languages like OCaML and F#.
The main feature I'm proposing is the possibility of using `typedef` to define sum types. They can be thought of as type enumerations.
This will, in some cases, reduce the need for `dynamic` making for sounder typing.
For example `json.decode` would no longer return `dynamic` but JSON a sum type, something like:
```
typedef JSON is Map | List | Literal;
```
Sum types could power a new behaviour of switch case that resolves the type based on the typed enumerated. Kind of like `assert` and `if` does with contemporary `is` syntax.
```
typedef T is A | B | C;
...
void foo(T arg) {
switch(arg) {
case A: // here arg is casted to A
break;
case B: // here arg is casted to B
break;
case C: // here arg is casted to C
break;
}
}
```
A better syntax for this type of switch case might be of order, maybe something like dart-lang/sdk#57173.
```
typedef T is A | B | C;
...
void foo(T arg) {
switch(arg) {
case A -> ... // here arg is A
case B -> ... // here arg is B
case C -> ... // here arg is C
}
}
```
This would be a powered down version of OCaML and F# `match with` as I've not included a proposition for type deconstruction, which would probably require tuples (or more in general product types) as discussed in dart-lang/linter#68.
Contributor guide
Assessment
This issue has not been assessed yet.