如何将函数作为值传入另一个函数并获取返回结果?
函数作为参数传递并获取返回值的实现方案
我一直尝试实现将函数作为值传入另一个函数并获取返回结果的功能,但始终未找到合适的解决方案。实际代码中该逻辑会运行在循环内,核心需求是即使值为私有,也能获取其更新后的结果。
以下是伪代码示例:
String myFunction(Function otherFunction) { return otherFunction.call(); } String anotherFunction() { return "Hello World!"; }
调用myFunction(anotherFunction);应返回"Hello World!"。
Java 实现方案
Java 8及以上版本支持函数式编程,可直接使用内置的Supplier接口(无参数、返回结果的函数式接口)来实现需求:
import java.util.function.Supplier; public class FunctionPassingDemo { // 接收Supplier类型的函数参数 public static String myFunction(Supplier<String> func) { return func.get(); // 对应伪代码中的call()方法 } public static String anotherFunction() { return "Hello World!"; } public static void main(String[] args) { // 传递方法引用调用 String result = myFunction(FunctionPassingDemo::anotherFunction); System.out.println(result); // 输出:Hello World! } }
针对循环内获取私有变量最新值的核心需求,示例代码如下:
public class PrivateValueDemo { private int privateCounter = 0; // 私有方法:更新并返回私有变量值 private int updateAndGetCounter() { return ++privateCounter; } public void runLoop() { for (int i = 0; i < 5; i++) { // 传入私有方法的引用,每次调用都能拿到最新的私有变量值 int currentValue = myFunction(this::updateAndGetCounter); System.out.println("当前私有计数器值:" + currentValue); } } // 通用的函数接收方法 private <T> T myFunction(Supplier<T> func) { return func.get(); } public static void main(String[] args) { new PrivateValueDemo().runLoop(); } }
运行后会依次输出1到5,每次调用都能获取到私有变量更新后的结果。
Python 实现方案
Python原生支持函数作为一等对象,直接传递函数即可实现需求:
def my_function(other_func): return other_func() def another_function(): return "Hello World!" # 调用示例 result = my_function(another_function) print(result) # 输出:Hello World!
循环内获取私有变量(Python用下划线约定私有)最新值的示例:
class PrivateValueDemo: def __init__(self): self._private_counter = 0 def _update_and_get_counter(self): self._private_counter += 1 return self._private_counter def run_loop(self): for _ in range(5): current_value = self._my_function(self._update_and_get_counter) print(f"当前私有计数器值:{current_value}") def _my_function(self, func): return func() if __name__ == "__main__": demo = PrivateValueDemo() demo.run_loop()
内容的提问来源于stack exchange,提问作者Voxel
相关产品推荐
相关产品推荐

