Question mark operator proposals
FeepingCreature
feepingcreature at gmail.com
Fri May 12 13:44:20 UTC 2023
On Friday, 12 May 2023 at 13:02:25 UTC, Dadoum wrote:
> There were at some point discussions in the forum about error
> handling and adding a potential question mark operator in D,
> and I would support it personally since it would allow to force
> caller of a function to handle some recoverable errors which
> can happen frequently (especially with `@mustuse`).
>
> ...
>
> ```d
> struct ServerError {
> int error;
> string message;
> }
>
> alias ServerResponse = SumType!(string, ServerError);
>
> Account account = AuthServer.authenticate(mail, password)?;
> ```
Neat also has this
(https://neat-lang.github.io/manual.html#sum-type):
```d
struct ServerError {
int error;
string message;
}
alias ServerResponse = (string | fail ServerError);
string account = AuthServer.authenticate(mail, password)?;
// More verbose form
string account = AuthServer.authenticate(mail, password)
.case(ServerError err: return err);
```
`fail` is a keyword of sumtype entries. Any expression of the
form `x?` will return all entries marked as `fail`, yielding a
sumtype of the remaining types, or the type if there's only one.
It seems to work pretty well. The interaction with class methods
is dubious though, because it means that a submethod cannot ever
return an error that a supermethod didn't account for. (Arguably
that's not *wrong...*)
More information about the Digitalmars-d
mailing list