How to make a lambda expression define toString in Java 8?
static <X,Y> Function<X,Y> withName(Function<X,Y> func, String name) {
return new Function<X, Y>() {
@Override
public Y apply(X x) {
return func.apply(x);
}
@Override
public String toString() {
return name;
}
};
}
/* Predicate, BiFunction, ... */
{// using
myFunction(
withName(a->a+1, "add one"),
withName((a,b)->a+b, "sum")
);
}
Short answer, you can't. @FunctionalInterface
s cannot be used to "override" methods from Object
.
You can implement Formattable
however, with a virtual extension method. Note: code below is UNTESTED:
@FunctionalInterface
public interface ToStringInterface
extends Formattable
{
String asString();
@Override
default void formatTo(Formatter formatter, int flags, int width, int precision)
{
formatter.format("%s", this);
// Or maybe even better:
formatter.out().append(this.asString());
}
}
I propose this solution since you are using String.format()
which makes use of this interface.
Or you can just define your own interface. Or even write a wrapper for this interface which calls .toString()
in .asString()
. Choices are many.