sum_types and sum_types_generator packages together define a code generator enabling sum-types in Dart.
NOTE: v0.2.0 is a major update with backward-incompatible changes.
In example/lib/src/ you can find a few sum-type declarations and the code generated for them.
This one models the natural numbers (with zero):
import 'package:meta/meta.dart';
import 'package:sum_types/sum_types.dart';
@SumType()
class Nat extends _$Nat {
const Nat.zero() : super(zero: const Unit());
const Nat.next(Nat value) : super(next: value);
Nat operator +(Nat other) => this.iswitch(
zero: () => other,
next: (next) => Nat.next(next + other),
);
int toInt() => this.iswitch(
zero: () => 0,
next: (next) => 1 + next.toInt(),
);
}
Core:
const Nat.zero()
)Nat.toInt()
)Case<_Nat>(name: "next")
→ Nat.next(Nat.zero())
)Either<Left, Right>
)iswitch
iswitcho
(with otherwise:
case)Sugar:
Case<void>(name: "zero")
→ Nat.zero()
)Case<String>()
→ JSON.string("some")
)Trivia:
Serialization-deserialization support through product-types interoperability:
NatRecord<Self>
, Nat.load<T extends NatRecord<T>>(T rec)
)Nat.dump<T>(T Function({Unit zero, T next} make))
)Find the upcoming development plans in the project planner.