I wrote an article like this the other day.
I want to get rid of the over-nested () https://qiita.com/tkturbo/items/04960f4e3e7226de3b46
I wrote here
// using custom object
const applier = (val)=>{
const o={
value : val,
apply : (unary)=>{ o.value=unary(o.value); return o; }
};
return o;
};
console.log(applier(name).apply(f0).apply(f1).apply(f2).value);
Let's convert this to java today.
Applier.java
public class Applier<T> {
private T value;
public Applier(T value) {
this.value = value;
}
// import java.util.function.Function;
public <R> Applier<R> apply(Function<? super T, ? extends R> appliable){
return new Applier<R>(appliable.apply(this.value));
}
public T get() { return this.value; }
}
That's right if you use the java.util.function.Function interface.
It is this one line that will be the key.
public <R> Applier<R> apply(Function<? super T, ? extends R> appliable){
Because of this, it is possible to process even if the input and output have different types.
For example
System.out.println(
new Applier<String>("0001")
.apply(v->Integer.parseInt(v,10))
.apply(v->v+1)
.apply(v->String.format("%04d", v))
.get()
);
It can be used like this.
personally,
return new Applier<R>(appliable.apply(this.value));
This one line feels strange, so I want to write it like this.
public class Applier<T> {
private T value;
public Applier(T value) {
this.value = value;
}
public <R> Applier<R> apply(Appliable<? super T, ? extends R> appliable){
return new Applier<R>(appliable.applyTo(this.value));
}
public T get() { return this.value; }
@FunctionalInterface
public static interface Appliable<T, R> {
public R applyTo(T value);
}
}
The public static interface is used to prevent namespace pollution.
Recommended Posts