问题

假设我在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;};

这很难看。有没有办法摆脱Voidtype参数?


#1 热门回答(231 赞)

使用Supplier如果它什么都不需要。

如果没有返回任何内容,请使用Consumer

如果它没有,请使用Runnable


#2 热门回答(82 赞)

你可以使用一个小帮助函数来转换aRunnable到650501725(例如,可以将它放在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"));

#3 热门回答(35 赞)

lambda:

() -> { System.out.println("Do nothing!"); };

实际上代表了一个接口的实现,如:

public interface Something {
    void action();
}

这与你定义的完全不同。这就是你得到错误的原因。

既然你不能扩展你的@FunctionalInterface,也不能推出一个全新的,那么我认为你没有太多的选择。你可以使用Optional<T>接口来表示缺少某些值(返回类型或方法参数)。但是,这不会使lambda体更简单。


原文链接