toNullable method

T? toNullable()

Creates a T? value from this. Useful when converting a value 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 Some case, e.g.:

final Option<int> option = Some(22);
final nrOfApples = option.toNullable();
if (nrOfApples != null) {
  print(nrOfApples);
}

Instead, use pattern matching for that:

final Option<int> option = Some(22);
if (option case Some(v: final nrOfApples)) {
  print(nrOfApples);
}

Implementation

T? toNullable() => switch (this) {
      Some(:T v) => v,
      None() => null,
    };