match<U> method
U
match<U>({
- required U err(
- E e
- required U ok(
- T v
Alternative to doing pattern matching with switch
expressions.
Makes pattern matching simpler to invoke, given match being a class
member; however, Result
and Option
pattern matching snippets (VSCode)
can be leveraged to make working with built-in pattern matching
(switch
and case
) a breeze.
While this method can be used as a weaker switch expression replacement,
it cannot replace switch statements, which are different and allow to
return a value from the "outer" function
(on the other hand, a return in ok
or err
will only return a
value from match; the same applies for switch expressions).
Example with match
:
bool myFn() {
final Result<int, String> result = Ok(9);
final msg = result.match(
// NB: returned values are assigned to msg
(number) => 'the lucky number is: $number',
(failure) => 'failure happened: $failure',
);
return true; // myFn returns true
}
Same example with a switch
expression:
bool myFn() {
final Result<int, String> result = Ok(9);
final msg = switch (result) {
// NB: returned values are assigned to msg
// it would be possible to distinguish between specific
// patterns directly here, e.g., by uncommenting:
// Ok(v: 0) => 'special case (0)',
Ok(v: final number) => 'the lucky number is: $number',
Err(e: final failure) => 'failure happened: $failure',
};
return true; // myFn returns true
}
Different example with a switch
statement (NB: different use case):
bool myFn() {
final Result<int, String> result = Ok(9);
switch (result) {
case Ok():
return true; // myFn returns true
case Err():
return false; // myFn returns false
}
}
Implementation
U match<U>({
required U Function(E e) err,
required U Function(T v) ok,
}) =>
switch (this) {
Ok(:T v) => ok(v),
Err(:E e) => err(e),
};