com.github.dakusui.crest.core.ChainedFunction Maven / Gradle / Ivy
package com.github.dakusui.crest.core;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
public interface ChainedFunction extends Function {
@Override
ChainedFunction andThen(Function super R, ? extends V> after);
ChainedFunction, ?> previous();
Function, R> chained();
static ChainedFunction chain(ChainedFunction super T, ? extends S> function, Function super S, ? extends R> next) {
return new Impl(function, next);
}
/**
* Creates a {@code ChainedFunction} from a given function {@code func}.
* Returned function does not have one previous to it. In other words, it will
* be a 'head' of a chain.
*
* @param func A function from which a returned function is created.
* @param Input
* @param Output
*
* @return created {@code ChainedFunction}
*/
static ChainedFunction create(Function super T, R> func) {
return new ChainedFunction() {
@Override
public ChainedFunction andThen(Function super R, ? extends V> after) {
return chain(this, after);
}
@Override
public ChainedFunction previous() {
return null;
}
@SuppressWarnings("unchecked")
@Override
public Function chained() {
return (Function) func;
}
@Override
public R apply(T t) {
return chained().apply(t);
}
@Override
public String toString() {
return chained().toString();
}
};
}
class Impl implements ChainedFunction {
private final Function super S, ? extends R> func;
private final ChainedFunction super T, ? extends S> previous;
Impl(ChainedFunction super T, ? extends S> previous, Function super S, ? extends R> func) {
this.previous = previous;
this.func = requireNonNull(func);
}
@SuppressWarnings("unchecked")
@Override
public R apply(T t) {
return this.chained().apply(this.previous().apply(t));
}
@Override
public ChainedFunction andThen(Function super R, ? extends V> after) {
return ChainedFunction.chain(this, after);
}
@SuppressWarnings("unchecked")
@Override
public ChainedFunction previous() {
return (ChainedFunction) previous;
}
@SuppressWarnings("unchecked")
@Override
public Function chained() {
return (Function) func;
}
@Override
public String toString() {
return previous().toString() + chained().toString();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy