'Could somebody demystify what I'm doing with anonymous class/lambda?

I'm building a JavaFX app and I've discovered the joy of

FXMLloader.setControllerFactory(setControllerFactory​(Callback<Class<?>,Object> controllerFactory)

I went off a searched example to get my code working:

            loader.setControllerFactory(c -> {
               return new MyController(dialog, seed);
            });

It's beautifully simple and clean and now I can define intended controllers in my FXML files but I can construct the controllers with much more complexity/seeding that doesn't happen during injection. Sorry, I'm not really understanding what took place there. I'm sure that's a lambda or an anonymous class. Could somebody please demystify this for me? I'm not sharp with lambdas. They always look attractive and the scoping access for local variables is always handy but they confuse the heck out of me.

In particular... The setControllerFactory needs to be passed an instance X of Callback<P,R> with generics P->Class<?> and R->Object so that something can do X.call(Class<?>) which returns an Object?

What/where did I define a Class<?> thing here? How would I code this without any lambdas/anonymous classes?



Solution 1:[1]

It (sort of) decomposes as follows

c ->       // c is the Class<?> parameter, which is not used
{    // Scope of Callback<Class<?>, Object>> lambda method body
     return new MyController(dialog, seed);    // The <Object> being returned
});

At some point the lambda gets called with a Class<?>, it ignores it and returns a new controller.

Equivalent anonymous class could be made by implementing Callback<Class<?>, Object> as

Callback<Class<?>, Object> f = new Callback<>() {
    public Object call(Class<?> ignored) {
        return new MyController(dialog, seed);
    }
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1