Java 8 lambda Void 参数

新手上路,请多包涵

假设我在 Java 8 中有以下功能接口:

 interface Action<T, U> {
   U execute(T t);
}

在某些情况下,我需要一个没有参数或返回类型的操作。所以我写了这样的东西:

 Action<Void, Void> a = () -> { System.out.println("Do nothing!"); };

但是,它给了我编译错误,我需要把它写成

Action<Void, Void> a = (Void v) -> { System.out.println("Do nothing!"); return null;};

这是丑陋的。有没有办法摆脱 Void 类型参数?

原文由 Wickoo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 649
2 个回答

您所追求的语法可以通过一个将 Runnable 转换为 Action<Void, Void> 的小辅助函数来实现(例如,您可以将其放在 Action 中):

 public static Action<Void, Void> action(Runnable runnable) {
    return (v) -> {
        runnable.run();
        return null;
    };
}

// Somewhere else in your code
 Action<Void, Void> action = action(() -> System.out.println("foo"));

原文由 Matt 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Supplier 如果它什么都不带,但返回一些东西。

使用 Consumer 如果它需要一些东西,但什么都不返回。

使用 Callable 如果它返回结果并可能抛出(最类似于 Thunk 在一般 CS 术语中)。

使用 Runnable 如果两者都不做并且不能抛出。

原文由 x1a0 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题