How can I write a readable string for lambda?

I will try to be very careful here with my wording, since lambda is, in fact, only the signature of the method and the body.

The premise to my question is that it would be very useful to maintain a brief lambda syntax and to be able to recognize a person (string) to identify it, that is, when you exit the system.

Previously, with anonymous classes, I could always override toString.

final Runnable runnable = new Runnable() {  
  @Override public void run() { System.out.println("1"); }
  @Override public String toString() { return "anonymous-1"; }
}

Scenarios

Listed below are the scenarios in which I found that I need to return to the code in order to be able to depilator

  • One use case for this is where you have the lambda argument of another function, and in your logs you want to print the specific lambda / implementation that passes. Say, for example, you had a Consumer who took a string, and you had implementations of this that would print a greeting as well as a string in several languages. It would be nice to name the strategies, say "in French", "in Spanish."
  • You have a Set Runnable, say, each of which will be applied in turn, and you want to exit the contents of this set.

Problem Since there are no accompanying toString, then everything that you get in the logs when you try to exit the lambda link, for example:

MyClass$$Lambda$1/424058530@1c20c684

The approaches

  • , , , .
  • ... , .

.

+4
1

, , - Runnable-with-toString factory.

static Runnable makeRunnable(Runnable r, Supplier<String> toStringFn) {
    return new Runnable() {
        public void run() { r.run(); }
        public String toString() { return toStringFn.get(); }
    };
}

, , :

Runnable r = makeRunnable(() -> System.out.println("1"), 
                          () ->  "anonymous-1");

( , toString , String Supplier<String>.)

+7

Source: https://habr.com/ru/post/1611935/


All Articles