Can I override toString method of functional interface? Or rephrase. Is there elegant way to change anonymous inner class that implements functional interface and overrides toString method with lambdas? Can I override toString when I create lamba expression in JDK8.
interface Iface {
void do();
}
main() {
Iface iface = () -> /*do something*/
System.out.println(iface); // I would like to see anything useful in output
}
Can I override toString for iface?
If you own the interface, you can do something like this
public interface Iface {
void doIt();
default Iface withToString(final String toString) {
return new Iface(){
public void doIt(){
Iface.this.doIt();
}
public String toString(){
return toString;
}
};
}
}
public static void main(String... args){
Iface iface = () -> {};
iface = iface.withToString("anything useful");
System.out.println(iface); // prints "anything useful" to output
}
Of course in practice it's fun to use something more interesting than just a String. It's not too much more code to capture the arguments and return value from doIt (if there were any) and generate a custom string with another functional interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With