Java 中的嵌套函数 [英] Nested functions in Java

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

问题描述

Java 编程语言是否有任何扩展可以创建嵌套函数?

Are there any extensions for the Java programming language that make it possible to create nested functions?

在很多情况下,我需要创建仅在另一个方法或 for 循环的上下文中使用一次的方法.到目前为止,我一直无法在 Java 中完成此操作,尽管它可以在 JavaScript 中轻松完成.

There are many situations where I need to create methods that are only used once in the context of another method or for-loop. I've been unable to accomplish this in Java so far, even though it can be done easily in JavaScript.

例如,这不能在标准 Java 中完成:

For example, this can't be done in standard Java:

for(int i = 1; i < 100; i++){
    times(2); // Multiply i by 2 and print i
    times(i); // Square i and then print the result

    public void times(int num){

        i *= num;
        System.out.println(i);
    }
}

推荐答案

Java 8 引入了 lambdas.

Java 8 introduces lambdas.

java.util.function.BiConsumer<Integer, Integer> times = (i, num) -> {
    i *= num;
    System.out.println(i);
};
for (int i = 1; i < 100; i++) {
    times.accept(i, 2); //multiply i by 2 and print i
    times.accept(i, i); //square i and then print the result
}

() -> 语法适用于任何只定义一个方法的接口.所以你可以将它与 Runnable 一起使用,但它不能与 List 一起使用.

The () -> syntax works on any interface that defines exactly one method. So you can use it with Runnable but it doesn't work with List.

BiConsumerjava.util.function.

值得注意的是,在幕后,这定义了一个匿名类并实例化它.times 是对实例的引用.

It's worth noting that under the hood, this defines an anonymous class and instantiates it. times is a reference to the instance.

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

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