Skip to content

Instantly share code, notes, and snippets.

@astashov
Created March 15, 2015 18:00
Show Gist options
  • Save astashov/e1554eb55284188f22f0 to your computer and use it in GitHub Desktop.
Save astashov/e1554eb55284188f22f0 to your computer and use it in GitHub Desktop.
Maybe in Dart
library maybe;
abstract class Maybe<T> {
T get value;
bool get isEmpty;
}
class Nothing extends Maybe {
get value => null;
bool get isEmpty => true;
String toString() => "Nothing";
}
var nothing = new Nothing();
class Just<T> extends Maybe<T> {
T _value;
T get value => _value;
Just(this._value);
bool get isEmpty => false;
String toString() => "Just $value";
}
Maybe<double> divide(double a, double b) {
if (b == 0) {
return nothing;
} else {
return new Just(a / b);
}
}
void main() {
var result = divide(5.0, 2.0);
if (result is Just) {
print("Result - $result");
} else if (result is Nothing) {
print(result);
}
switch(result.isEmpty) {
case true: print("Result - $result"); break;
case false: print(result); break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment