com.github.tonivade.purefun.CheckedFunction1 Maven / Gradle / Ivy
/*
* Copyright (c) 2018-2019, Antonio Gabriel Muñoz Conejo
* Distributed under the terms of the MIT License
*/
package com.github.tonivade.purefun;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Option;
import com.github.tonivade.purefun.type.Try;
@FunctionalInterface
public interface CheckedFunction1 extends Recoverable {
R apply(A value) throws Throwable;
default CheckedFunction1 andThen(CheckedFunction1 after) {
return (A value) -> after.apply(apply(value));
}
default CheckedFunction1 compose(CheckedFunction1 before) {
return (B value) -> apply(before.apply(value));
}
default Function1 unchecked() {
return recover(this::sneakyThrow);
}
default Function1 recover(Function1 mapper) {
return value -> {
try {
return apply(value);
} catch(Throwable e) {
return mapper.apply(e);
}
};
}
default Function1> liftOption() {
return liftTry().andThen(Try::toOption);
}
default Function1> liftEither() {
return liftTry().andThen(Try::toEither);
}
default Function1> liftTry() {
return value -> Try.of(() -> apply(value));
}
static CheckedFunction1 identity() {
return value -> value;
}
static CheckedFunction1 failure(Producer supplier) {
return value -> { throw supplier.get(); };
}
static CheckedFunction1 of(CheckedFunction1 reference) {
return reference;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy