Skip to content

Commit

Permalink
types: Documents the Result type
Browse files Browse the repository at this point in the history
  • Loading branch information
hexaredecimal committed Oct 24, 2024
1 parent f65d614 commit 367bbf3
Showing 1 changed file with 49 additions and 12 deletions.
61 changes: 49 additions & 12 deletions src/blazing/types/Result.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package blazing.types;

import blazing.BlazingLog;
import java.util.function.Function;
import java.util.function.Supplier;

/**
Expand All @@ -11,15 +10,34 @@
* @param <E> The type of the error that is returned
*/
public class Result<T, E> {

private Result() {}

/**
* Used to represent a successful result
* @param <T>
* @param <E>
* @param value
* @return
*/
public static <T, E> Result<T, E> ok(T value) {
return new Ok(value);
}

/**
* Used to represent an error
* @param <T>
* @param <E>
* @param value
* @return
*/
public static <T, E> Result<T, E> err(E value) {
return new Err(value);
}

/**
* Unwraps the Ok value and panics if there is an error
* @return
*/
public T unwrap() {
if (this instanceof Err err) {
var error = err.getErr();
Expand All @@ -34,6 +52,11 @@ public T unwrap() {
return (T) ok.getValue();
}

/**
* Unwraps an Ok value and returns the provided value if there is an error
* @param value
* @return
*/
public T unwrapOr(T value) {
if (this instanceof Err) {
return value;
Expand All @@ -42,6 +65,11 @@ public T unwrapOr(T value) {
return (T) ok.getValue();
}

/**
* Unwraps an Ok value and calls the supplier method if there is an error
* @param fx
* @return
*/
public T unwrapOrElse(Supplier<T> fx) {
if (this instanceof Err) {
return fx.get();
Expand All @@ -50,6 +78,10 @@ public T unwrapOrElse(Supplier<T> fx) {
return (T) ok.getValue();
}

/**
* Unwraps the error and panics if the value is Ok
* @return
*/
public E unwrapErr() {
if (this instanceof Ok) {
String msg = "Attempt to unwrap value of Result.Ok()";
Expand All @@ -60,19 +92,25 @@ public E unwrapErr() {
return (E) err.getErr();
}


/**
* Checks if the value is an error
* @return
*/
public boolean isErr() {
return this instanceof Err;
}

/**
* Checks if the value is ok
* @return
*/
public boolean isOk() {
return this instanceof Ok;
}

private static class Ok<T, E> extends Result<T, E> {

private final T value;

private T value = null;
private Ok() {}
private Ok(T value) {
this.value = value;
}
Expand All @@ -88,20 +126,19 @@ public String toString() {
}

private static class Err<T, E> extends Result<T, E> {

private final T err;

private T error = null;
private Err() {}
private Err(T err) {
this.err = err;
this.error = err;
}

private T getErr() {
return err;
return error;
}

@Override
public String toString() {
return "Result.Err(" + err + ")";
return "Result.Err(" + error + ")";
}
}
}

0 comments on commit 367bbf3

Please sign in to comment.