Runnable::new vs new Runnable()
Asked Answered
B

5

63

Why doesn't the first of the following examples work?

  • run(R::new); method R.run is not called.
  • run(new R()); method R.run is called.

Both examples are compiled-able.

public class ConstructorRefVsNew {

  public static void main(String[] args) {
      new ConstructorRefVsNew().run(R::new);
      System.out.println("-----------------------");
      new ConstructorRefVsNew().run(new R());
  }

  void run(Runnable r) {
      r.run();
  }

  static class R implements Runnable {

      R() {
          System.out.println("R constructor runs");
      }

      @Override
      public void run() {
          System.out.println("R.run runs");
      }
  }
}

The output is:

  R constructor runs
  -----------------------
  R constructor runs
  R.run runs

In the first example, the R constructor is called, it returns lambda (which is not object):

But then how is it possible, that the example is compiled successfully?

Brownedoff answered 7/1, 2019 at 10:15 Comment(2)
Note that Runnable runnable = R::new; runnable instanceof R -> falseJalbert
I don't know about Java specifically but new is usually an indicator that you want to allocate some memory that you promise you will clean up yourself. R::new just sounds like a factory method, a static function in R that creates and returns an instance of Runnable. If this instance is not captured by assigning it to a variable it might be cleaned up the moment it goes out of scope.Simms
P
57

Your run method takes a Runnable instance, and that explains why run(new R()) works with the R implementation.

R::new is not equivalent to new R(). It can fit the signature of a Supplier<Runnable> (or similar functional interfaces), but R::new cannot be used as a Runnable implemented with your R class.

A version of your run method that can takeR::new could look like this (but this would be unnecessarily complex):

void run(Supplier<Runnable> r) {
    r.get().run();
}

Why does it compile?

Because the compiler can make a Runnable out of the constructor call, and that would be equivalent to this lambda expression version:

new ConstructorRefVsNew().run(() -> {
    new R(); //discarded result, but this is the run() body
});

The same applies to these statements:

Runnable runnable = () -> new R();
new ConstructorRefVsNew().run(runnable);
Runnable runnable2 = R::new;
new ConstructorRefVsNew().run(runnable2);

But, as you can notice, the Runnable created with R::new does just call new R() in its run method body.


A valid use of a method reference to execute R#run could use an instance, like this (but you'd surely rather use the r instance directly, in this case):

R r = new R();
new ConstructorRefVsNew().run(r::run);
Prosenchyma answered 7/1, 2019 at 10:18 Comment(2)
Should we assume, that java compiler created from my method run(Runnable r) -> run(Supplier<Runnable> r)?Brownedoff
@Brownedoff I edited the answer. The compiler made () -> {new R();} out of R::new in that context.Prosenchyma
A
24

The first example:

new ConstructorRefVsNew().run(R::new);

is more or less equivalent to:

new ConstructorRefVsNew().run( () -> {new R();} );

The effect is you just create an instance of R but do not call its run method.

Adonai answered 7/1, 2019 at 10:23 Comment(1)
It means, that I have two nested runnable. On the first method run is called only.Brownedoff
B
10

Compare two calls:

((Runnable)() -> new R()).run();
new R().run();

By ((Runnable)() -> new R()) or ((Runnable) R::new) , you create a new Runnable which does nothing1.

By new R(), you create an instance of the R class where the run method is well-defined.


1 Actually, it creates an object of R which has no impact on execution.


I was thinking of treating 2 invocations identically without modifying the main method. We would need to overload run(Runnable) with run(Supplier<Runnable>).

class ConstructorRefVsNew {

    public static void main(String[] args) {
        new ConstructorRefVsNew().run(R::new);
        System.out.println("-----------------------");
        new ConstructorRefVsNew().run(new R());
    }

    void run(Runnable r) {
        r.run();
    }

    void run(Supplier<Runnable> s) {
        run(s.get());
    }

    static class R implements Runnable { ... }
}
Bohun answered 7/1, 2019 at 10:28 Comment(0)
I
7

The run method expects a Runnable.

The easy case is new R(). In this case you know the result is an object of type R. R itself is a runnable, it has a run method, and that's how Java sees it.

But when you pass R::new something else is happening. What you tell it is to create an anonymous object compatible with a Runnable whose run method runs the operation you passed it.

The operation you passed it is not R's run method. The operation is the costructor of R. Thus, it's like you have passed it an anonymous class like:

new Runnable() {

     public void run() {
         new R();
     }
}

(Not all the details are the same, but this is the closest "classical" Java construct ).

R::new, when called, calls new R(). Nothing more, nothing less.

Issykkul answered 7/1, 2019 at 10:24 Comment(0)
T
0

Just my two cents here to give a more readable answer, for people are new to java lambda world.

What's this

  • R::new is using method reference, which emerged from java8, let you reuse existing method definitions and pass them just like lambdas. So when you write Runnable::new, actually it means () -> new R(), the result is a lambda;
  • new R() is calling the constructor of class R, and return an instance of that class, the result is a instance of R.

We are now clear about what are them, but how they works(why they are compiled-able)?

How it works

For new R(), it's very easy to understand what happened and I'll leave without explanation.

For Runnable::new which stands for () -> new R(), we need to know that Runnable is what we called the FunctionalInterface, and a functional interface is a interface with only one method, when we pass lambda to a method that accepts a functional interface as parameter, the lambda must matches the signature of that interface, and the action in lambda is filled to the body of that method.

The Runnable in JDK11 looks like this:

@FunctionalInterface
public interface Runnable {

    public abstract void run();
}

while the lambda () -> new R() is compatible with the method signature - accept nothing and return nothing, so the code works, and in this case, the runTime object of the passed-in parameter looks like this:

Runnable instance with run method {

    public void run() {
      new R();
    };
}

now we get to know why in this situation, only construction of R triggered.

What's more

We can achieve what run(new R()) does with lambda like this:

new ConstructorRefVsNew().run(() -> System.out.println("R.run runs"));

I finally realize the question comes very tricky that the given lambda Runnable::new is actually compatible with Runnable interface. You can define a customize functional interface called Foo or whatever to do the same thing

@FunctionalInterface
public interface Foo{

    public abstract void run();
}

public class ConstructorRefVsNew {

  public static void main(String[] args) {
      new ConstructorRefVsNew().run(R::new);
  }

  void run(Foo f) {
      f.run();
  }
}

and in this case, the R::new still works well while the new R() cannot be passed, which indicates that the question is not a big deal but a fascinating coincidence.

Twirl answered 17/3, 2020 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.