【发布时间】:2015-07-08 20:25:06
【问题描述】:
假设我在 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这个类型参数?
【问题讨论】:
-
如果你需要一个你定义的动作,这是不可能的。但是,您的第一个示例可能适合
Runnable,这是您正在寻找的Runnable r = () -> System.out.println("Do nothing!"); -
@BobTheBuilder 我不想使用该帖子中建议的消费者。
-
Matt 的回答使类型工作,但是调用者在得到 null 返回值时会做什么?
-
您可以祈祷并希望this post 中的建议 2 和 3 被 Java 9 接受!