Java 8 lambda Void参数 [英] Java 8 lambda Void argument

查看:187
本文介绍了Java 8 lambda Void参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have the following functional interface in Java 8:

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

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

And for some cases I need an action without arguments or return type. So I write something like this:

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

然而,它给我编译错误,我需要把它写成

However, it gives me compile error, I need to write it as

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

哪个很难看。有没有办法摆脱 Void 类型参数?

Which is ugly. Is there any way to get rid of the Void type parameter?

推荐答案

你后的语法是可能的,其将一个可运行一个小的辅助功能动作<空隙,空隙率> (例如,您可以将其放在行动):

The syntax you're after is possible with a little helper function that converts a Runnable into Action<Void, Void> (you can place it in Action for example):

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"));

这篇关于Java 8 lambda Void参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆