dart_scope_functions 1.0.0 copy "dart_scope_functions: ^1.0.0" to clipboard
dart_scope_functions: ^1.0.0 copied to clipboard

Kotlin-inspired scope functions implemented in Dart with the goal of executing a block of code within the context of an object

example/main.dart

import 'package:dart_scope_functions/dart_scope_functions.dart';

void main() {
  // Usage of `also`
  final listAlso = ['one', 'two', 'three'].also((it) {
    print('list before adding new element: $it');
    it.add('four');
  });
  print(listAlso); // [one, two, three, four]

  // Usage of `let` and `letWithElse`
  final listLet = [null, 1, 2, null, 3, null];
  print(listLet.elementAt(0)?.let((it) => it.toDouble())); // null
  print(listLet.elementAt(2)?.let((it) => it.toDouble())); // 2.0
  print(listLet
      .elementAt(0)
      .letWithElse((it) => it.toDouble(), orElse: 0.0)); // 0.0

  // Usage of `run`
  final hexNumberRegex = run(() {
    final digits = '0-9';
    final hexDigits = 'a-fA-F';
    final sign = '+-';

    return RegExp('[$sign]?[$digits$hexDigits]+');
  });
  print(hexNumberRegex.stringMatch('+123 -FFFF !%*& 88 XYZ')); // +123

  // Usage of `takeIf` and `takeUnless`
  const number = 94;
  final evenOrNull = number.takeIf((it) => it % 2 == 0);
  final oddOrNull = number.takeUnless((it) => it % 2 == 0);
  print("even: $evenOrNull, odd: $oddOrNull"); // even: 94, odd: null

  // Usage of `withDefault`
  final double? nullableNumber = null;
  final defaultOfNullableNumber = nullableNumber.withDefault(123.45);
  print('default value: $defaultOfNullableNumber');
}
14
likes
160
points
1.79k
downloads

Publisher

verified publisherbizjak.dev

Weekly Downloads

Kotlin-inspired scope functions implemented in Dart with the goal of executing a block of code within the context of an object

Repository (GitLab)
View/report issues

Topics

#kotlin #scope #function #scope-functions #utility

Documentation

API reference

License

BSD-3-Clause (license)

More

Packages that depend on dart_scope_functions