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 super T, ? extends U> func);
public abstract Try flatMap(Function super T, Try> 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 super T,? extends U> func) {
try {
return new Success<>(func.apply(value));
} catch (final Exception e) {
return new Failure<>(e);
}
}
@Override
public Try flatMap(final Function super T, Try> 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 super T,? extends U> func) {
return new Failure<>(this.getError());
}
@Override
public Try flatMap(final Function super T, Try> 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() + ")";
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy