Created
December 2, 2019 15:26
-
-
Save Schwusch/2b29c92ff130eb6a5c81320e33be539a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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