Optional.java

AKL City ยท akl-city.git

Branches > main > latest > files / src / main / java / dev / grahp / option / Optional.java

package dev.grahp.option;

import java.lang.RuntimeException;
import java.util.function.*;

// Make IBox and make this Box to avoid name collision
public class Optional<T> implements Box {
  private final T value;
  public final boolean present;

  public Optional() {
    present = false;
    value = null;
  }

  public Optional(T value) {
    this.value = value;
    present = true;
  }

  @Override
  public T val() {
    if (present) {
      return value;
    } else {
      throw new RuntimeException("Tried to unbox an empty box!");
    }
  }

  public <R> R then(Function<T, R> f) {
    if (present) {
      return f.apply(value);
    }

    return null;
  }

  public void then(Consumer<T> f) {
    if (present) {
      f.accept(value);
    }
  }

  public <R> R otherwise(Supplier<R> f) {
    if (!present) {
      return f.get();
    }

    return null;
  }

  public void otherwise(Runnable f) {
    if (!present) {
      f.run();
    }
  }

  public <R> R then(Function<T, R> f, Supplier<R> otherwise) {
    if (present) {
      return f.apply(value);
    }

    return otherwise.get();
  }

  public void then(Consumer<T> f, Runnable otherwise) {
    if (present) {
      f.accept(value);
    } else {
      otherwise.run();
    }
  }

  public <R> R then(Consumer<T> f, Supplier<R> otherwise) {
    if (present) {
      f.accept(value);
      return null;
    }

    return otherwise.get();
  }

  public <R> R then(Function<T, R> f, Runnable otherwise) {
    if (present) {
      return f.apply(value);
    }

    otherwise.run();
    return null;
  }

  @Override
  public String toString() {
    return present ? "Optional[" + value.toString() + "]"
                   : "Optional[]";
  }
}