Nested functions in Java

后端 未结 6 1396
礼貌的吻别
礼貌的吻别 2020-11-27 15:53

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

6条回答
  •  没有蜡笔的小新
    2020-11-27 16:24

    Java 8 introduces lambdas.

    java.util.function.BiConsumer 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.

提交回复
热议问题