如何优雅地创建一个返回lambda的返回值或什么都不返回的函数? [英] How to elegantly create a function which returns a lambda's return value or nothing?

查看:186
本文介绍了如何优雅地创建一个返回lambda的返回值或什么都不返回的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java编写一个更高阶的函数,该函数需要一个lambda并返回labmda的返回值,或者如果lambda没有返回类型则不返回任何内容.

I want to write a higher order function in Java which takes a lambda and returns the labmda's return value or does not return anything if the lambda has no return type.

科特林中,我会做类似的事情:

In Kotlin, I would do something like this:

fun <T> test(block: () -> T): T {
    val r = block()
    // ...
    return r
}

由于万一没有返回 的情况下Unit将是T,因此它将起作用.

Since Unit will be T in case nothing is returned, this will work.

Java 中,我只能提出以下建议:

In Java I could only come up with this:

public class Main {

    private static <T> T test(Supplier<T> s) {
        T t = s.get();
        // ...
        return t;
    }

    private static void test(Runnable r) {
        // ...
        r.run();
    }

    public static void main(String args[]) {
        test(() -> System.out.println("Hello")); // returns void
        test(() -> 5); // return an Int
    }
}

当我想返回lambda的返回值时,我不得不重载test,如果lambda不返回任何内容,则给它一个Runnable.

I had to overload test giving it a Supplier<T> when I want to return the lambda's return value and a Runnable if the lambda does not return anything.

有没有更好的方法而不过载?

Is there a better way without overloading?

由于void(但Void可以)不能代替T,所以我不知道如何.

Since void (but Void could) cannot take the place of T, I don't see how.

推荐答案

有没有更好的方法而不过载?

Is there a better way without overloading?

否.

您最好的办法是通过从Runnable重载中调用Supplier重载来避免重载中的重复:

The best you can do is to avoid duplication in the overloads, by calling the Supplier overload from the Runnable overload:

private static void test(Runnable r) {
  test(() -> { r.run(); return null; });
}

这篇关于如何优雅地创建一个返回lambda的返回值或什么都不返回的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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