OLD | NEW |
---|---|
(Empty) | |
1 import 'dart:async'; | |
2 | |
3 /// [Try] is similar to Haskell monad, where | |
4 /// a computation may throw an exception. | |
5 /// There is no checking of passing null into | |
6 /// the value, so be mindful. | |
7 class Try<T> { | |
8 final T _val; | |
9 final StackTrace _stackTrace; | |
10 final Exception _err; | |
11 | |
12 Try.from(this._val) | |
13 : _err = null, | |
14 _stackTrace = null; | |
15 | |
16 Try.error(this._err, this._stackTrace) : _val = null; | |
17 | |
18 Try<S> bind<S>(S f(T)) { | |
19 if (_err != null) { | |
20 return new Try.error(_err, _stackTrace); | |
21 } | |
22 | |
23 try { | |
24 return new Try<S>.from(f(_val)); | |
25 } catch (ex, stackTrace) { | |
26 return new Try<S>.error(ex, stackTrace); | |
27 } | |
28 } | |
29 | |
30 Future<Try<S>> bindAsync<S>(Future<S> f(T)) async { | |
Bill Hesse
2017/08/23 15:41:25
Future itself has an error channel and a value cha
mkroghj
2017/08/25 09:28:28
The idea for bindAsync is to change Try<Future<X>>
| |
31 if (_err != null) { | |
32 return new Try.error(_err, _stackTrace); | |
33 } | |
34 | |
35 try { | |
36 return new Try.from(await f(_val)); | |
37 } catch (ex, stackTrace) { | |
38 return new Try.error(ex, stackTrace); | |
39 } | |
40 } | |
41 | |
42 void fold(caseErr(Exception), caseVal(T)) { | |
43 if (_err != null) | |
Johnni Winther
2017/08/23 12:40:47
Add curly braces (dangling statements are brittle)
| |
44 caseErr(_err); | |
45 else | |
46 caseVal(_val); | |
47 } | |
48 | |
49 bool isError() => _err != null; | |
Johnni Winther
2017/08/23 12:40:47
Make this a getter:
bool get isError => _error
| |
50 | |
51 Exception getError() => _err; | |
Johnni Winther
2017/08/23 12:40:47
Ditto.
| |
52 StackTrace getStackTrace() => _stackTrace; | |
Johnni Winther
2017/08/23 12:40:47
Ditto.
| |
53 | |
54 T get() => _val; | |
Johnni Winther
2017/08/23 12:40:47
Make this a getter:
bool get value => _val;
| |
55 | |
56 T getOrDefault(T defval) => _err != null ? defval : _val; | |
57 } | |
58 | |
59 Try<T> tryStart<T>(T action()) { | |
60 return new Try<int>.from(0).bind<T>((dummy) => action()); | |
61 } | |
62 | |
63 Future<Try<T>> tryStartAsync<T>(Future<T> action()) { | |
64 return new Try<int>.from(0).bindAsync<T>((dummy) => action()); | |
65 } | |
OLD | NEW |