Java 8 lambda Void argument

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

    You can create a sub-interface for that special case:

    interface Command extends Action {
      default Void execute(Void v) {
        execute();
        return null;
      }
      void execute();
    }
    

    It uses a default method to override the inherited parameterized method Void execute(Void), delegating the call to the simpler method void execute().

    The result is that it's much simpler to use:

    Command c = () -> System.out.println("Do nothing!");
    

提交回复
热议问题