Anonymous or lambda function inside method parameter

Viewed 46

I saw following block of code in my teams codebase :

boolean value = fun(data->{
    data.setProperty();
    return data;
})

Above fun is a method which accepts objects of class called Data. However I have doubt:

I just saw data object only passed inside fun i.e there was no line of code like Data data = new Data() before above code snippet. Thus how above code snippet works ? It looks similar to lambda or anonymous functions. But I have never seen such code block in Java before. data object was present in whole .java file at only one place and that was above code block. I got curius how it's possible to use some object variable without declaring before.

1 Answers

if you have for example

@FunctionalInterface
interface UnaryOperator<T> {
    void callMeWithData(T someData);
}

void fun(UnaryOperator<String> operator) {
    String theData = "hello";
    operator.callMeWithData(theData);
}

fun((data) -> {
   // prints "hello"
   System.out.println(data);
});

What you do here is to supply a function that acts like the callMeWithData method which also takes one parameter and returns nothing. Before Lambdas you would have to do

fun(new UnaryOperator<String>() {
    @Override
    public void callMeWithData(String someData) {
        System.out.println(data);
    }
});

So the type of data is defined inside the single method in UnaryOperator, it's filled within fn and then received in your lambda as data (which is just an arbitrary name you can use here)

Related