google / google/built_value.dart

Union Types

Open
#395 29 comments 11 reactions 1 assignee Claimed by @davidmorgan View on GitHub
p2 / feature request
Dominant language
Dart
Stars
886
Forks
195
Avg merge
1d 11h
Merged PRs (30d)
4

Description

Along with data classes and enum classes, dart also lacks a support for defining custom union types. I think built_value could contain another generator for union types that followed the same principles as enum and data classes. The union class should be:

- immutable
- comparable
- serializable
- implement toString

I think it would look something like this:

```dart
/// how the user defines a union
@union
const myUnion = const [int, String];
```

generated in a .g.dart file:
```dart
/// the generated union class. It should be immutable
/// but probably not a built_value since it only takes
/// 1 parameter to build a new value.
@immutable
class MyUnion {
/// every union type has `value` and `type` accessors
/// `value` must be dynamic, and be casted to `type`
final dynamic value;

final Type type;

/// a typed constructor is generated for each possible type
MyUnion.int(int value)
: value = value,
type = int;

MyUnion.string(String value)
: value = value,
type = String;

/// a convience function for switching on type
/// similiar switching on types using Kotlin's when statement.
T when(
T intCallback(int value),
T stringCallback(String value),
) {
switch (type) {
case int:
return intCallback(value as int);
case String:
return stringCallback(value as String);
default:
throw Exception('wtf');
}
}

String toString() => (newBuiltValueToStringHelper('MyUnion')
..add('value', value)
..add('type', type))
.toString();

int hashCode() => $jf($jc($jc(0, value.hashCode), type.hashCode));

@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! MyUnion) return false;
return type == other.type && value == other.value;
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.