Naming(toString) Lambda-Expressions for Debugging purpose

前端 未结 2 719
情歌与酒
情歌与酒 2020-12-22 06:09

Sometimes it is usefull to name lambdas. Especially when you pass them around as parameter.

A realy simple example is

public class Main {
    publi         


        
2条回答
  •  天命终不由人
    2020-12-22 06:37

    Here's an alternative that comes to mind:

    static  Predicate nameIt(String name, Predicate pred) {
        return new Predicate() {
            public String toString() { return name; }
            public boolean test(T t) { return pred.test(t); }
        };
    }
    

    This seems pretty simple. Although I haven't benchmarked it, it seems like it ought to be pretty fast. It adds a single object and one method call, and it avoids boxing/unboxing overhead.

    The drawback is that you have to write a little function like this for every functional interface for which you want to provide named instances.

提交回复
热议问题