如何优雅地创建一个返回lambda的返回值或什么都不返回的函数? [英] How to elegantly create a function which returns a lambda's return value or nothing?
问题描述
我想用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屋!