-
Notifications
You must be signed in to change notification settings - Fork 213
Modeling a "Result" type is possible, but difficult #3337
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I can see that this is mostly about handling values and errors using some kind of case analysis, but if you are also interested in chaining (that is, methods often named as |
Thanks Eric! I care less about chaining but those are all good references. |
It's correct that the "you've exhausted all the other options, so what remains must be the type" promotion isn't something we support for sealed types. It works for union types, One reason is an implementation issue. The "is this switch exhaustive, or what's missing" algorithm is separate from the type inference algorithm, and runs after (because it needs to know the static types to answer that question). You'll notice that even switches don't work without writing the type for the second element: switch (willSucceed) {
case ValueResult<int, String> _:
print('value: ${result.value}'); // Works
case _:
print('error: ${result.error}'); // Doesn't work, not promoted to `ErrorResult`.
} (I hope the compiler might be able to use the exhaustiveness check to know that it doesn't need to do a the last check, but that's long after type inference.) |
|
@matanlurey If you are interested in Rust types like Result, check out this new library: https://pub.dev/packages/rust_core . Rust's result type has been completely implemented and more. |
I filed #3501 to address adding such a type directly to the SDK or a first-party package, and maybe implementing chaining operators such as |
Playground: https://dartpad.dev/cb41699ff72a41cb9412ef48f47cf824.
I've really enjoyed Dart's 3 class modifiers and pattern matching.
I'm trying to implement a
Result<T, E>
type, similar to Rust'sstd::result
:As you can see in my playground, it works! It's just a bit more complicated than I'd expect for a sealed type with only two sub-types (I can see how the implementation as-is works for traditional enum-like types). Here are the individual test cases I wrote:
Maybe there is a better way to do this I don't know about or this can serve as inspiration for type inference improvements.
Thanks!
The text was updated successfully, but these errors were encountered: