dart_scope_functions
is a Dart utility library that implements Kotlin-inspired scope functions. These functions provide a convenient way to execute a block of code within the context of an object, making the code more readable and expressive.
- Execute blocks of code within the context of an object.
- Chain multiple operations on an object in a readable manner.
- Conditional operations on objects, including nullable types.
Add dart_scope_functions
to your pubspec.yaml
file:
dependencies:
dart_scope_functions: latest
Then, run pub get
to install the package.
Import the library:
import 'package:dart_scope_functions/dart_scope_functions.dart';
void main() {
var result = 'Hello'.also((it) {
print(it); // Prints 'Hello'
}).let((it) {
return it.length;
});
print(result); // Prints 5
var nullableString = null;
var defaultString = nullableString.withDefault('Default Value');
print(defaultString); // Prints 'Default Value'
var conditionResult = 42.takeIf((it) => it > 40);
print(conditionResult); // Prints 42
var runResult = run(() {
return 'Running a block';
});
print(runResult); // Prints 'Running a block'
}
Calls the specified function block
with this value as its argument and returns this
value.
block
: A function to execute with the value.- Returns: The original value.
Calls the specified function block
with this
value as its argument and returns its result.
block
: A function to execute with the value.- Returns: The result of
block
.
Returns this
value if it satisfies the given predicament
or null
if it doesn't.
predicament
: A condition to evaluate.- Returns: The value if it satisfies the condition, otherwise
null
.
Returns this
value if it does not satisfy the given predicament
or null
if it does.
predicament
: A condition to evaluate.- Returns: The value if it does not satisfy the condition, otherwise
null
.
Calls the specified function block
with this
value as its argument and returns its result. If this
is null
, it returns the provided orElse
value.
block
: A function to execute with the value if it's notnull
.orElse
: A default value to return ifthis
isnull
.- Returns: The result of
block
ororElse
.
Returns this
value if it's not null
, otherwise returns the provided defaultValue
.
defaultValue
: A default value to return ifthis
isnull
.- Returns: The value or the default value.
Calls the specified function block
and returns its result.
block
: A function to execute.- Returns: The result of
block
.