패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.6.0

maybe_just_nothing

Dart로 작성된 급속 실행을 하는 오래된 Maybe 모나드의 또 다른 변형입니다。

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
38.8만
좋아요
11
Pub 점수
160

패키지 설치

flutter pub add maybe_just_nothing

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

maybe_just_nothing은 즉시 실행을 갖춘 Maybe 모나드의 변형을 구현한 Dart 패키지로, 선택적 값을 안전하고 표현적으로 다루기 위해 설계되었습니다. 존재할 수도 있고 아닐 수도 있는 값을 캡슐화함으로써 null 관련 오류를 방지하는 함수형 접근법을 제공합니다. 이 패키지는 모든 주요 플랫폼을 지원하며 Dart 프로젝트에 원활하게 통합됩니다. API는 명확성과 체인 가능한 연산을 강조하여 런타임 예외 없이 견고한 null 안전 패턴을 찾는 개발자에게 이상적입니다.

사용 사례

  • API에서 선택적 데이터 처리
  • 널 가능 연산의 안전한 체이닝
  • 널 체크를 함수형 스타일로 대체
  • 오류 없는 데이터 변환 파이프라인
  • 복잡한 조건 논리 간소화

주요 기능

  • 값의 급격한 평가
  • map 및 flatMap을 사용한 함수형 조합
  • 널 안전 연산
  • 최소한의 보일러플레이트
  • 크로스 플랫폼 지원

적합한 대상

  • 함수형 패턴을 사용하는 Dart 개발자
  • 강력한 null 처리가 필요한 프로젝트
  • 클린 코드 관행을 채택하는 팀
  • 복잡한 데이터 흐름을 가진 애플리케이션
  • 모나드에 익숙한 개발자

고려 사항

  • 초보자에게 학습 곡선을 유도할 수 있음
  • 지연 평가 요구 사항에 적합하지 않습니다
  • 모나딕 개념에 대한 이해가 필요합니다
  • 복잡한 상태에 대한 값 래핑으로 제한
  • 깊은 체인에서의 성능 오버헤드

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Maybe Just Nothing

Yet another variation of the good old Maybe monad with eager execution written in Dart.

Creating maybe-values

Internally, Maybe is an abstract class with two implementations: Just and Nothing.

The most common scenario is probably discarding null from nullable values:

int? nullableValue;
final val = Just(nullableValue).type<int>(); // val is either Just<int> or Nothing<int>
final doubled = val.map((x) => x * 2);
doubled.ifPresent(print); // would print the doubled value of nullableValue if it's not null

Nullable values can also be wrapped in Just:

int? nullableValue;
final val = Just(nullableValue); // val is Just<int?>
final justNull = Maybe(null); // creates Just<void>

The Nothing value may be created either typed or untyped:

final nothing1 = Nothing(); // Nothing<Object?>
final nothing2 = Nothing<int>(); // Nothing<int>
final nothing3 = Nothing<String?>(); // Nothing<String?>

You may even distinguish between presence and absence of nulls themselves:

Maybe<void> yay = Just(null); // Just<Null>
Maybe<void> nay = Nothing<void>(); // Nothing<Null>

Mapping values

Mapping means transformation of the wrapped value by applying a function. Since Maybe itself is immutable, mapping operations do not actually modify the value. Instead, they always return another Maybe.

Just(2).map((x) => x * 2).ifPresent(print); // prints "4"

If the mapping function also returns a Maybe, use flatMap():

Maybe<int> triple(int x) => Just(x).map((x) => x * 3);

Just(2).flatMap(triple).ifPresent(print); // prints "6"

An operation on two maybe-values can be performed using merge():

final two = Just(2);
final three = Just(3);

two.merge(three, (x, y) => x + y).ifPresent(print); // prints "5"

Filtering values

Filtering is checking whether the maybe-value satisfies a certain condition. If it does, the value remains intact, otherwise Nothing is returned.

To filter by the value itself, use the where():

Just(2).where((x) => x.isEven).ifPresent(print); // prints "2"
Just(3).where((x) => x.isEven).ifPresent(print); // 3 is odd, so nothing happens

To filter by type, use type<T>():

final maybeInt = Just(2).type<int>(); // Just<int>
final maybeString = Just(2).type<String>(); // Nothing<String>

Fallback chain

The chain() method implements the Chain of Responsibility design pattern. It accepts another maybe-value of the same type. If the current value is Nothing, the next value in the chain gets returned.

Another way to implement the same idea is to use the fallback() method. It accepts a "fallback" function which returns another maybe-value of the same type. If the current value is Nothing, this fallback function will be called and its result will be returned. You can provide several fallback functions. They will be called in sequence until a Just value is received.


Nothing<int>()
  .chain(Nothing<int>()) // this will be skipped
  .chain(Just(2)) // this value is not empty, so it will be used
  .chain(Just(3)) // this value will NOT be used
  .ifPresent(print); // prints "2"

// Same with fallback()
Nothing<int>()
  .fallback(() => Nothing<int>()) // this result will be skipped
  .fallback(() => Just(2)) // this function returns a non-empty value
  .fallback(() => Just(3)) // this function will NOT be called
  .ifPresent(print); // prints "2"

Consuming the value

The intention of Maybe is to give it the consumer function instead of retrieving the value. This is the most concise and clear way of using it.

Maybe a;
a
  ..ifPresent(print)
  ..ifNothing(() {/* do something else*/});

Reading the value

Sometimes, however, you need the actual value. In such cases you'll have to provide the default value as well.

In the simplest scenario, use or():

Maybe<int> a;
final value = a.or(0); // value is 0
final valueFromFuture = await a.orAsync(Future.value(0)); // value is 0

A provider function can be specified instead of the default value:

Maybe<int> a;
final value = a.orGet(() => 0); // value is 0
final valueFromFuture = await a.orGetAsync(() async => 0); // value is 0

If there is no default value, an exception can be thrown:

Maybe<int> a;
final value = a.orThrow(() => 'Oops!');

In some rare cases, it can be convenient to check for emptiness directly:

Maybe<int> myInt;

if (myInt is Just<int>) {
  print(myInt.value); // .value is guaranteed to be non-null
}

if (myInt is Nothing) {
  print('The value is missing');
}

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트