wartman/kit

Improve/Unify Result and Maybe

Closed this issue · 0 comments

Implement a small change to Result's API:

  • unwrap should no longer throw an error: instead, it returns the value of Ok or null. orThrow(), without an argument, can handle the current behavior.

...as well as a much bigger change:

  • Convert Result into an abstract that will automatically convert haxe.Exception and null/Nothing types into Error(...) and everything else into Ok(...). This should make things much more ergonomic and slightly more rust-like.
  • We should also consider renaming Nothing to NoValue to prepare for the stuff being done for Haxe 5 where we can just deprecate our current implementation.
  • Maybe will be changed into a simple typedef: typedef Maybe<T> = Result<T, Nothing>.

This will make the following code valid:

function testResult(input:Int):Result<Int> {
  if (input > 3) return new Exception('Input out of bounds');
  return input + 1;
}

We could also add a utility in intercept thrown errors and convert them to Results:

function testResult(input:Int) return Result.intercept(() -> {
  if (input > 3) throw 'Input out of bounds';
  return input + 1;
}); // returns a Result<Int, Exception>