Skip to content

Instantly share code, notes, and snippets.

@Schwusch
Created December 2, 2019 15:26
Show Gist options
  • Save Schwusch/2b29c92ff130eb6a5c81320e33be539a to your computer and use it in GitHub Desktop.
Save Schwusch/2b29c92ff130eb6a5c81320e33be539a to your computer and use it in GitHub Desktop.
extension ScopingFunctions<T> on T {
/// Calls the specified function [block] with `this` value
/// as its argument and returns its result.
R let<R>(R Function(T) block) => block(this as T);
/// Calls the specified function [block] with `this` value
/// as its argument and returns `this` value.
T also(void Function(T) block) {
block(this as T);
return this as T;
}
}
// Example usage
main() {
Map<String, String> maybeNull;
maybeNull = {'hello': 'world'};
final bar = maybeNull?.also((absolutelyNotNull) {
absolutelyNotNull.addAll({'mickey': 'mouse'});
});
print(bar); // {hello: world, mickey: mouse}
final int nrOfKeys = bar?.let((mapNotNull) => mapNotNull.keys.length);
print(nrOfKeys); // 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment