Page MenuHomeDevCentral

Option::orElse should use a closure, not a default value
Open, HighPublic

Description

See https://devcentral.nasqueron.org/D3846#59556

Plan is to:

  • Allow a scalar default value with or:
    • Add abstract or method in Option
    • Some Implement as return $this
    • None rename orElse -> or
  • Allow a closure with orElse so it's only executed on None
    • Change prototype in Option to accept Callable as type
    • None can use return $callable()

Event Timeline

dereckson triaged this task as High priority.Tue, Nov 4, 02:31
dereckson created this task.

New plan

  • Rename the method described above, with the same current behavior, to getValueOr / getValueOrElse
  • Address the code for Result too, not only for Option
  • Introduce or / orElse as returning Option/Result so we can chain methods
  • Bump OmniTools major version (breaking BC) -> opportunity to remove deprecated PHP 7 string utilities code like str_contains str_starts_with

That will allow expressions like:

Obsidian User::resolveUserID
public static function resolveUserID ($expression) : Option {
    return self::get_user_from_username($expression)
        ->orElse(self::get_user_from_email($expression))
        ->map(fn($user) => $user->id);
}