errToNullable method

E? errToNullable()

Creates an E? value from this. Useful when converting an error and passing it as argument where a nullable type is expected, e.g., third-party libraries that expect nullable types.

Anti-patterns

This method should not be used to match only the Err case, e.g.:

final Result<int, String> result = Ok(42);
final errorText = result.errToNullable();
if (errorText != null) {
  print(errorText);
}

Instead, use pattern matching for that:

final Result<int, String> result = Ok(42);
if (foo case Err(e: final errorText)) {
  print(errorText);
}

Implementation

E? errToNullable() => switch (this) {
      Ok() => null,
      Err(:E e) => e,
    };