Skip to content
Advertisement

Nested functions in Java

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement