All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.outbrain.ob1k.concurrent.Try Maven / Gradle / Ivy

The newest version!
package com.outbrain.ob1k.concurrent;

import com.google.common.base.Function;

/**
 * represent either a result or an error using two ADTs - Success and Failure.
 *
 * @author aronen
 */
public abstract class Try {
  // to prevent any further derivation.
  private Try() {}

  public abstract boolean isSuccess();
  public abstract T getValue();
  public abstract Throwable getError();
  public abstract  Try map(Function func);
  public abstract  Try flatMap(Function> func);
  public abstract Try recover(Function func);

  public static  Try fromValue(final T value) {
    return new Success<>(value);
  }

  public static  Try fromError(final Throwable error) {
    return new Failure<>(error);
  }

  public static class Success extends Try {
    private final T value;

    public Success(final T value) {
      this.value = value;
    }

    @Override
    public boolean isSuccess() {
      return true;
    }

    @Override
    public T getValue() {
      return value;
    }

    @Override
    public Throwable getError() {
      return null;
    }

    @Override
    public  Try map(final Function func) {
      try {
        return new Success<>(func.apply(value));
      } catch (final Exception e) {
        return new Failure<>(e);
      }
    }

    @Override
    public  Try flatMap(final Function> func) {
      try {
        return func.apply(getValue());
      } catch (final Exception e) {
        return new Failure<>(e);
      }
    }


    @Override
    public Try recover(final Function func) {
      return this;
    }

    @Override
    public String toString() {
      return "Success(" + value + ")";
    }
  }

  public static final class Failure extends Try {
    private final Throwable error;

    public Failure(final Throwable error) {
      this.error = error;
    }

    @Override
    public boolean isSuccess() {
      return false;
    }

    @Override
    public T getValue() {
      return null;
    }

    @Override
    public Throwable getError() {
      return error;
    }

    @Override
    public  Try map(final Function func) {
      return new Failure<>(this.getError());
    }

    @Override
    public  Try flatMap(final Function> func) {
      return new Failure<>(this.getError());
    }

    @Override
    public Try recover(final Function func) {
      try {
        return new Success<>(func.apply(error));
      } catch (final Exception e) {
        return new Failure<>(e);
      }
    }

    @Override
    public String toString() {
      return "Failure(" + error.toString() + ")";
    }
  }

}