FLUTTER ECOSYSTEM

tonio-ramirez/optional.dart

Dart用のOptional型の実装

optional.dart のプロジェクト画像
Stars
39
Forks
7
最終プッシュ(UTC)
2022/04/12
プロジェクト状態
公開中
Juan Antonio Ramírez GitHub avatar
GITHUB User

Juan Antonio Ramírez ↗

Tech42 Solutions, LLCSan Juan, PR公式サイト ↗
言語Dart

このリポジトリが公開するパッケージ

使用している依存関係

依存関係一覧 6 件

元の README

以下は英語原文のスナップショットです。最新版は GitHub をご覧ください。

README を開く / 閉じる

https://github.com/tonio-ramirez/optional.dart/workflows/tests/badge.svg?branch=master Coverage Status

Optional.dart

Optional.dart is an implementation of the Optional type, inspired by Java 8's Optional class.

Optional helps avoid null reference errors by wrapping values in an object that holds information regarding whether the value is present or not.

For example, when applying a set of operations to a value, any of which might return null, you can get rid of the null checks by using Optional.map():

String? getString() {
  // ..
  if (condition) {
    return null;
  } else {
    return "12";
  }
}

int? calculateSomething(String str) {
  // ...
  if (someCondition) {
    return null;
  } else {
    return 3 + int.parse(str);
  }
} 

double? calculateSomethingElse(int val) {
  // ...
  if (anotherCondition) {
    return null;
  } else {
    return val * 1.42;
  }
}

void main() {
  
  // before
  
  String? str;
  int? i;
  double? d;
  
  str = getString();
  
  if (str != null) {
    i = calculateSomething(str);
  }
  
  if (i != null) {
    d = calculateSomethingElse(i);
  }
  
  if (d != null) {
    print(d);
  }
  
  // with Optional
  
  Optional.ofNullable(getString())
    .map(calculateSomething)
    .map(calculateSomethingElse)
    .ifPresent(print);
}