Java 8 lambda Void argument

前端 未结 9 666
臣服心动
臣服心动 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:08

    That is not possible. A function that has a non-void return type (even if it's Void) has to return a value. However you could add static methods to Action that allows you to "create" a Action:

    interface Action {
       U execute(T t);
    
       public static Action create(Runnable r) {
           return (t) -> {r.run(); return null;};
       }
    
       public static  Action create(Action action) {
           return action;
       } 
    }
    

    That would allow you to write the following:

    // create action from Runnable
    Action.create(()-> System.out.println("Hello World")).execute(null);
    // create normal action
    System.out.println(Action.create((Integer i) -> "number: " + i).execute(100));
    

提交回复
热议问题