FLUTTER ECOSYSTEM

tonio-ramirez/optional.dart

다트를 위한 옵셔널 타입의 구현

optional.dart 프로젝트 이미지
Stars
39
Forks
7
최근 푸시(UTC)
2022. 4. 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);
}