nlfiedler / oxidized

Dart package with Rust-like types such as Option and Result.
https://pub.dev/packages/oxidized
BSD 3-Clause "New" or "Revised" License
40 stars 10 forks source link

How to create Result<void, Failure>? #10

Open AlexanderFarkas opened 3 years ago

AlexanderFarkas commented 3 years ago

It's not allowed to leave Result.ok empty. How to achieve void behaviour? Null is pretty awful workaround.

nlfiedler commented 3 years ago

From what I can tell, Dart does not have a "unit" type like Rust, and void is "special". What's more, the Void type in dart:ffi can only be used in the Dart VM, and worse, it cannot be instantiated. The only way I can see to create a Result with a void value type is with a void function and use Result.of(), like so:

void func() {
  return;
}
var result = Result.of(() => func());

The type of result is Result<void, dynamic>

AlexanderFarkas commented 3 years ago

Couldn't you create Result.okVoid, which doesn't return anything?

nlfiedler commented 3 years ago

I tried a few things and nothing would pass the compiler, it insists that the value must be of type T and neither null nor void can satisfy that requirement. Technically the example I gave earlier isn't quite right, but at least it compiles without issue.

lemunozm commented 3 years ago

For that issue, Dartz library (which has a kind of Result called Either) offers an Unit type that makes the trick and is very visual throughout the code. Maybe something similar can be implemented here.

nlfiedler commented 3 years ago

Let me know if commit a692c01 is what you're looking for.

Stumblinbear commented 1 year ago

Couldn't you do this by removing the extends Object bound on all of the generics (except for E)? I don't see any particular reason why they're restricted to Object.

Removing them shouldn't break existing code (as loosening bounds shouldn't do that), and would permit Result<void, E> and returning Result.ok(null) instead of the unit type. I've tested this in a local dependency_override and it seems to work fine.

nlfiedler commented 1 year ago

@Stumblinbear Your contributions would be welcome, please feel free to submit a PR.