rust_like_result 2.4.2 rust_like_result: ^2.4.2 copied to clipboard
The Result<T> type implemented in Ok<T> and Err<T> types with unwrap methods.
import 'dart:io';
import 'package:rust_like_result/rust_like_result.dart';
void main() async {
// Ok:
Result<Map> res = Ok({'Forward': 'yes', 'Back': 'no'});
print(res); // Ok({Forward: yes, Back: no})
print(res is Ok ? 'Ok' : 'Err'); // Ok
print(res.unwrap); // {Forward: yes, Back: no}
print(res.unwrapOrDefault({})); // {Forward: yes, Back: no}
print(res.unwrapOrElse((e) => {'error': e})); // {Forward: yes, Back: no}
// Err:
res = Err(ArgumentError('Bad name'));
print(res); // Err(Invalid argument(s): Bad name)
print(res is Ok ? 'Ok' : 'Err'); // Err
// print(res.unwrap); // raises exception 'Invalid argument(s): Bad name'
print(res.unwrapOrDefault({})); // {}
print(res.unwrapOrElse(
(e) => {'Got error': e})); // {Got error: Invalid argument(s): Bad name}
// tryAsResult...() - calls function and return result as Ok, or Err if exception was raised:
// ignore: omit_local_variable_types
Result ok =
await tryAsResultAsync(() => File('notExistsFile').rename('newPath'));
print(ok); // Err(Bad state: FileSystemException: Cannot rename ...
ok = await tryAsResultAsync(() => Directory('.').list());
print(ok); // Ok(Instance of '_ControllerStream<FileSystemEntity>')
ok = tryAsResultSync(() => File('notExistsFile').renameSync('newPath'));
print(ok); // Err(Bad state: FileSystemException ...
ok = tryAsResultSync(() => Directory('.').listSync());
print(ok); // Ok([File:...
// Pipe operator stays Err as is, but calls right-side function on val of the left-side Ok.
var r = Err<int>(ArgumentError('Lalala')) | (((x) => x * 2));
print(r); // Err(Invalid argument(s): Lalala)
r = Ok(123) | (x) => x * 2;
print(r); // Ok(246)
r = (Ok(123) | (x) => x * 2) | (x) => x + 1;
// ^----------------------^ - parentheses need to be used. I'm sorry.
print(r); // Ok(247)
r = Ok(123).pipe((x) => x * 2).pipe((x) => x + 1);
// ^------------------^ it's better, hm?
print(r); // Ok(247)
// .pipe() allows a long cascading:
var r2 = Ok(123)
.pipe((x) => x * 2)
.pipe((x) => x + 4)
.pipe((x) => x * 2)
.pipe((x) => x / 5)
.pipe((x) => 'My answer is: $x')
.unwrapOrElse((e) => 'Was some error:$e');
print(r2); // My answer is: 100.0
// .pipe() allows a long cascading:
var r3 = Err(ArgumentError('Your argument is bad'))
.pipe((x) => x * 2)
.pipe((x) => x + 4)
.pipe((x) => x * 2)
.pipe((x) => x / 5)
.pipe((x) => 'My answer is: $x')
.unwrapOrElse((e) => 'Was some error:$e');
print(r3); // Was some error:Invalid argument(s): Your argument is bad
var r4 = Ok(123)
.pipe((x) => x * 2)
.pipe((x) => x + 4)
// You don't need wrap error with Err() like:
// .pipe((x) => Err(AssertionError('My assertion error')))
// Be simple:
.pipe((x) => AssertionError('My assertion error'))
.pipe((x) => x / 5)
.pipe((x) => 'My answer is: $x')
.unwrapOrElse((e) => 'Was some error:$e');
print(r4); // Was some error:Assertion failed: "My assertion error"
}