1

I'm not sure what's going on here. Here's an interface:

public interface AppInit {
  void create(Environment var1);
}

Here's some class's method:

  public static StandaloneModule create(AppInit appInit) {
    return new StandaloneModule(appInit);
  }

And here's how that method is being called:

StandaloneModule.create(Main::configure)

But that parameter method's signature is:

static void configure(final Environment environment) {
  ...

Why does this compile?

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • 1
    Voodoo. https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13.2 – passer-by Apr 11 '22 at 00:17
  • Possible dupe of [What is a SAM type?](https://stackoverflow.com/questions/17913409/what-is-a-sam-type-in-java), since `AppInit` is a SAM-type and `Main::configure` is a method reference. You can also take a look at the accepted answer on [How to pass a function as a parameter?](https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java). – shriakhilc Apr 11 '22 at 00:28

1 Answers1

2

Your interface is a functional interface (i.e., one abstract method). In particular it is a Consumer of type Environment. A consumer takes an argument and returns nothing. So it just consumes the argument, usually applying some type to it. Here is a more common example.

interface Consumer {
      void apply(String arg);
}

public class ConsumerDemo  {
    public static void main(String [] args) {
        SomeMethod(System.out::println);
        
    }
    
    public static void SomeMethod(Consumer con) {
        con.apply("Hello, World!");
    }
}

prints

Hello, World!

The interface need not be explicitly implemented. The compiler takes care of that by finding the appropriate interface and creating what would normally be an anonymous class.

The above was called with a method reference. It could also be called as a lambda.

a -> System.out.println(a)

Here con.apply("Hello, World!") would pass the string to to a and it would be printed.

WJS
  • 36,363
  • 4
  • 24
  • 39