λ1005: Prefer GetOrElse over Match

A Match that returns the inner value or a fallback should be expressed as GetOrElse.

Cause

Match is called on an Option<T>, Either<L, R> or Result<T> where the success branch is the identity function (x => x or Identity) and the error branch produces a value of the same type.

Reason for rule

Match is the most general way to leave a monad; it is the escape hatch that every other operation could be written with. When the success branch just returns the value unchanged, the call re-implements GetOrElse. Using the dedicated method names the intent and is shorter.

How to fix violations

Replace the Match call with GetOrElse, passing the former none/left/error argument. A code fix is available.

Examples

Disallowed

static int Example(Option<int> option)
    => option.Match(none: 42, some: x => x);

static int Example(Option<int> option)
    => option.Match(none: () => 42, some: Identity);

static int Example(Result<int> result)
    => result.Match(ok: x => x, error: _ => 42);

Allowed

static int Example(Option<int> option)
    => option.GetOrElse(42);

static int Example(Option<int> option)
    => option.GetOrElse(() => 42);

static int Example(Result<int> result)
    => result.GetOrElse(_ => 42);

// The success branch transforms the value, so this is a legitimate Match.
static int Example(Option<int> option)
    => option.Match(none: 42, some: x => x + 1);