when_extension 0.1.2 when_extension: ^0.1.2 copied to clipboard
Dart library with when annotation for generating custom when extensions and extension methods for dart builtin types
when_extension #
when
extension methods for Dart. Inspired by Kotlin's when
expression.
This library contains @when
annotation for generating custom when
extensions
and extension methods for dart builtin types.
Class when #
Similar to sealed
classes in Kotlin (discriminated unions) a when
extension method for a single level class hierarchy can be generated using the
@when
annotation. All classes must be defined in the same file.
//types.dart:
import 'package:when/when.dart';
part 'types.g.dart';
@when
abstract class Expr {}
class Value implements Expr {
int value;
Value({this.value});
}
class Add implements Expr {
Expr e1;
Expr e2;
Add({this.e1, this.e2});
}
A when extension method on Expr
function will be generated in the
types.g.dart
file. And can be used as follows:
int eval(Expr expr) {
return expr.when(
value: (v) => v.value,
add: (a) => eval(a.e1) + eval(a.e2),
any: () => 0,
);
}
The method takes an optional named function argument per subclass and an any
named argument that will called if none of the provided arguments matches. If
any
is not provided and no argument matches an exception will be thrown at
runtime.
Enum when #
An enum
can also be annotated with @when
to generate a when
extension
method:
//types.dart:
import 'package:when/when.dart';
part 'types.g.dart';
@when
enum Color {
red,
green,
blue,
}
final r = Color.red;
final result = r.when(
red: () => 1,
green: () => 2,
any: () => 3,
);
//result: 1
String.when #
import 'package:when/when.dart';
final s = 'aaa';
final result = s.when(
{
'aaa': () => 1,
'bbb': () => 2,
},
any: () => 3,
);
//result: 1
Setup #
Add the following to your pubspec.yaml:
dependencies:
when: ^0.1.0
dev_dependencies:
build_runner:
when_generator: ^0.1.0
If you are using the @when
annotation run:
pub run build_runner build