2

This doesn't work:

interface GenericFunctionalInterface {
    <T> void doSomething(T obj);
}
public class Foo {
    public final static GenericFunctionalInterface instance =
            (GenericFunctionalInterface) (a) -> {
                System.out.println(a);
    };
}

What is the correct syntax to instantiate instance?

Note

As the duplicate indicates, generic methods aren't able to be reduced to lambda expressions. But to add a bit to this, you can use the method address notation for a method that is or is not generic, provided that the method parameter's type is within the interface's generic type constraints.

E.g., we can write instance = System.out::println; because T extends Object, but we couldn't write instance = Number::doubleValue; because T does not extend Number (is not within the type constraints). Of course, if we wrote <T extends Number> void doSomething(T obj) we could define it as Number::doubleValue;.

See also method reference capture.

Joseph Nields
  • 5,527
  • 2
  • 32
  • 48

0 Answers0