Esta página ainda não foi traduzida, por isso é exibida em inglês. Ajude a traduzir

Either

A value that is either a failure Left(L) or a success Right(R) — the boundary type of the typed-error system.

sealed class Either<L, R> — Left(L value) | Right(R value) const factory Either.left(L value) | Either.right(R value) — dot-shorthand targets (Dart ≥ 3.10) T fold<T>(T Function(L left) ifLeft, T Function(R right) ifRight) static Either<Object, R> Either.catching<R>(R Function() block)

Lecture

Either<L, R> makes failure part of a function's signature: instead of throwing (invisible to the type system) or returning null (says nothing about why), you return Left(error) or Right(value). The class is sealed, so a switch over it is exhaustive — the compiler reminds you to handle the failure case.

The method set is Arrow 2.x's curated one: fold collapses both sides into one value, map/mapLeft transform one side, flatMap chains a dependent fallible step, and getOrNull/getOrElse bridge back to plain Dart. Either is meant to live at the boundary: inside a computation, prefer the either builder, where each step is one straight-line r.bind instead of a flatMap pyramid.

Demo 1 · Left, Right, and exhaustive switch

Demo 2 · fold, map, mapLeft, flatMap

Demo 3 · dot shorthands (Dart ≥ 3.10)

Either carries const factories Either.left / Either.right so Dart 3.10 dot shorthands resolve against it: wherever the context type is already Either — a return position, a switch-expression arm, the right side of == — you can drop the type name and write .left(error) / .right(value). Same objects as Left(…) / Right(…), just inferred from context.

Try it yourself

Exceptions and typed errors stay strictly separated: a thrown exception propagates out of typed-error code untouched. To capture a throw into an Either, be explicit with Either.catching (failure type Object) or Either.catchingWith (map the throw to your own failure type first). Exercise: make the failing parse print Left(bad input) instead of crashing.

Related: either builder — build Eithers with straight-line code · accumulation — collect every failure, not just the first · Either × pipelinesrights, lefts, sequence over chains · typed errors — full guide