Skip to content

Instantly share code, notes, and snippets.

@BenoitDuffez
Created May 19, 2021 13:29
Show Gist options
  • Save BenoitDuffez/866de31720b6e7970f73b9fdaa50597b to your computer and use it in GitHub Desktop.
Save BenoitDuffez/866de31720b6e7970f73b9fdaa50597b to your computer and use it in GitHub Desktop.
Dart let extension
import 'package:flutter_test/flutter_test.dart';
extension Let<T extends Object> on T? {
R let<R>(R Function(T) callback, {R Function()? or}) {
var self = this;
if (self != null) {
return callback(self);
}
if (or != null) {
return or();
}
R? nullReturn;
if (nullReturn is R) {
return nullReturn;
}
throw ArgumentError.notNull("or");
}
}
class A {}
void main() {
A? aNull;
A? aNonNull = A();
test('Test let(null) void', () {
aNull.let((it) => "bogus");
expect("OK", "OK");
});
test('Test let(null, or) void', () {
int a = 42;
aNull.let((it) => "bogus", or: () => a = 1000);
expect(1000, a);
});
test('Test let(null, or)', () => expect(aNull.let((it) => "bogus", or: () => "OK"), "OK"));
test('Test let(null, null or)', () => expect(aNull.let((it) => "bogus", or: () => null), null));
test('Test let(non null)', () => expect(aNonNull.let((it) => "OK"), "OK"));
test('Test let(non null, or)', () => expect(aNonNull.let((it) => "OK", or: () => "KO"), "OK"));
test('Test let(non null, null or)', () => expect(aNonNull.let((it) => "OK", or: () => null), "OK"));
test('Test letNonNull(null, or)', () => expect(aNull.let((it) => "bogus", or: () => "OK"), "OK"));
test('Test letNonNull(non null, or)', () => expect(aNonNull.let((it) => "OK", or: () => "KO"), "OK"));
test('Test letNonNull(non null, null or)', () => expect(aNonNull.let((it) => "OK", or: () => null), "OK"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment