![JAR search and dependency download from the Maven repository](/logo.png)
xdean.jex.extra.tryto.Success Maven / Gradle / Ivy
The newest version!
package xdean.jex.extra.tryto;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* @author [email protected]
*
*/
public class Success extends Try {
private final T value;
Success(T value) {
this.value = value;
}
@Override
public boolean isFailure() {
return false;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public T get() {
return value;
}
@Override
public Try foreach(Consumer f) {
f.accept(value);
return this;
}
@Override
public Try flatMap(Function> f) {
try {
return f.apply(value);
} catch (Exception e) {
return new Failure<>(e);
}
}
@Override
public Try map(Function f) {
return Try.to(() -> f.apply(value));
}
@Override
public Try filter(Predicate p) {
try {
if (p.test(value)) {
return this;
} else {
return new Failure<>(new NoSuchElementException("Predicate does not hold for " + value));
}
} catch (Exception e) {
return new Failure<>(e);
}
}
@Override
public Try recoverWith(Function> f) {
return this;
}
@Override
public Try recover(Function f) {
return this;
}
@Override
public Try failed() {
return new Failure<>(new UnsupportedOperationException("Success.failed"));
}
@Override
public Try transform(Function> s, Function> f) {
try {
return s.apply(this.get());
} catch (RuntimeException e) {
return new Failure<>(e);
}
}
@Override
public Try onException(Consumer f) {
// do nothing
return this;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy