rust_like_result 1.2.0 rust_like_result: ^1.2.0 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:
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)
}