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

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

问题描述

Java编程语言是否有任何扩展可以创建嵌套函数?在很多情况下,我需要创建在另一个方法或for循环的环境中仅使用一次的方法。到目前为止,我一直无法用Java实现它,尽管它可以在Javascript中轻松完成。



例如,这不能用标准Java :

  for(int i = 1; i <100; i ++){
times(2); //将我乘以2并打印i
次(i); // square i然后输出结果
public void times(int num){

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



$ div $解析方案

Java 8引入了lambdas。

  java.util.function.BiConsumer< Integer,Integer> times =(i,num) - > {
我* = num;
System.out.println(i);
};
for(int i = 1; i <100; i ++){
times.accept(i,2); //将我乘以2并打印i
times.accept(i,i); // square i然后输出结果
}

() - > 语法适用于任何定义了一种方法的接口。因此,您可以将它与 Runnable 一起使用,但它不适用于 List



BiConsumer 是由 java.util.function



值得注意的是,一个匿名类并实例化它。 是对实例的引用。


Are there any extensions for the Java programming language that make it possible to create nested functions? 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.

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 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
}

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.

BiConsumer is one of many functional interfaces provided by java.util.function.

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天全站免登陆