@@ -15,10 +15,21 @@ sealed class Result<S, E> {
1515 const Result ();
1616
1717 /// Build a [Result] that returns a [Success] .
18- factory Result .success (S s) => Success (s) ;
18+ const factory Result .success (S s) = Success ;
1919
2020 /// Build a [Result] that returns a [Error] .
21- factory Result .error (E e) => Error (e);
21+ const factory Result .error (E e) = Error ;
22+
23+ /// Get the [S] value IF it is a [Success] .
24+ ///
25+ /// It may throw [SuccessResultNotFoundException] if this result is actually
26+ /// an [Error] of [E] .
27+ ///
28+ /// Make sure to use [isSuccess] or `if (result case Success())` before
29+ /// accessing this method.
30+ ///
31+ /// You can also use [tryGetSuccess] if you're unsure of the possible result.
32+ S getOrThrow ();
2233
2334 /// Returns the value of [S] if any.
2435 S ? tryGetSuccess ();
@@ -97,6 +108,9 @@ final class Success<S, E> extends Result<S, E> {
97108 /// Success value
98109 S get success => _success;
99110
111+ @override
112+ S getOrThrow () => _success;
113+
100114 @override
101115 E ? tryGetError () => null ;
102116
@@ -153,6 +167,9 @@ final class Error<S, E> extends Result<S, E> {
153167 ) =>
154168 whenError (_error);
155169
170+ @override
171+ S getOrThrow () => throw SuccessResultNotFoundException ();
172+
156173 @override
157174 E tryGetError () => _error;
158175
@@ -165,3 +182,18 @@ final class Error<S, E> extends Result<S, E> {
165182 @override
166183 R ? whenSuccess <R >(R Function (S success) whenSuccess) => null ;
167184}
185+
186+ /// Thrown when getting the [S] type when none is available.
187+ final class SuccessResultNotFoundException <S , E > implements Exception {
188+ const SuccessResultNotFoundException ();
189+
190+ @override
191+ String toString () {
192+ return '''
193+ Tried to get the success value of [$S ], but none was found.
194+ Make sure you're checking for `isSuccess` before trying to get it through
195+ `getOrThrow`. You can also use `tryGetSuccess` if you're unsure or
196+ `if (result case Success())`
197+ ''' ;
198+ }
199+ }
0 commit comments