Convert a BiFunction into a Function in Java

Jordan Repovy :

Let's say I have the following enum :

public enum Foo {

  AAA(new A()::doA),
  BBB(new B()::doB),
  CCC(new C()::doC),
  DDD(new D()::doD);

  private Function<String, Number> do;

  Foo(Function<String, Number> do) {
    this.do = do;
  }

  public Function<String, Number> getDo() {
    return do;
  }  
}

Knowing that I must keep the getDo method with the exact same signature.

This works fine, if I do AAA.getDo().apply("two"), I will get 2 as a result. But the problem is that each call to the do method will always be done on the same instances of A, B, C and D. However, I need A, B, C or D to be a different instance at each call (Because these classes have fields, and I do not want these fields to keep their values throughout every call of the do method).

I thought about something like this :

AAA(
  A.class,
  A::doA);

However in this case A::doA is not a Function on an instance of A anymore, but a BiFunction to which I need to pass an instance of A as first parameter. But my getDo method still have to return a Function, and I do not see any way to turn my BiFunction and my A class, to a Function on A instance (we could imagine something like : (A::DoA).toFunction(A.class)).

ernest_k :

The method reference new A()::doA is bound to the one A object created when new A()::doA is evaluated to create the Function instance, i.e., when the enum value AAA is being created. new A() is executed immediately and a reference to its doA() method returned, just as though you had used someInstanceOfA::doA.

The way to fix it is to make the function itself call the constructor in the logic that's not run immediately:

AAA(s -> new A().doA(s)), 
BBB(s -> new B().doB(s)), 
CCC(s -> new C().doC(s)), 
DDD(s -> new D().doD(s));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133200&siteId=1