Skip to content
Advertisement

How to make a self-referencing lambda function that also references locals in Java?

I am trying to make a lambda function that references itself, and it is used as a callback for an asynchronous process, so I cannot use a loop. If I declare the function like so :

Consumer<String> func = argument -> {
    async_fn(func); // Call a function with func as callback
};

the compiler tells me The local variable func may not have been initialized. If I write it that way instead :

Consumer<String> func = argument -> {}; // pre-declare func
func = argument -> {
    async_fn(func); // Call an function with func as callback
};

the compiler says local variables referenced from a lambda expression must be final or effectively final. How could this be written so that the function references itself ? The function cannot be a class field because it references a method’s locals.

Advertisement

Answer

Although I do not understand why such a construct would be needed, you could do:

    Consumer<String> func = argument -> {}; // pre-declare func
    List<Consumer<String>> one = new ArrayList<>(Collections.singletonList(func));
    one.set(0, argument -> {
        async_fn(one.get(0)); // Call an function with func as callback
    });

Or use an array.

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