Java 8 lambda Void argument

前端 未结 9 651
臣服心动
臣服心动 2020-12-12 08:30

Let\'s say I have the following functional interface in Java 8:

interface Action {
   U execute(T t);
}

And for some cases I ne

9条回答
  •  攒了一身酷
    2020-12-12 09:11

    Add a static method inside your functional interface

    package example;
    
    interface Action {
           U execute(T t);
           static  Action invoke(Runnable runnable){
               return (v) -> {
                   runnable.run();
                    return null;
                };         
           }
        }
    
    public class Lambda {
    
    
        public static void main(String[] args) {
    
            Action a = Action.invoke(() -> System.out.println("Do nothing!"));
            Void t = null;
            a.execute(t);
        }
    
    }
    

    Output

    Do nothing!
    

提交回复
热议问题