2

I have Employee class:

public class Employee {

    private Long id;
    private String name;
    private String externalId;

    public Employee(Long id, String name, String externalId) {
        this.id = id;
        this.name = name;
        this.externalId = externalId;
    }

    //getters, setter
}

And employee service which returns an employee (NULL is possible).

private void performEmployeeProcessing() {
    Long employeeId = 2L;
    Object o = Optional.ofNullable(employeeService.getById(employeeId))
        .orElseGet(Employee::new, 1L, "", "");

    System.out.println(o);
}

It says compilation error

Employee::new, 1L, "", ""
Cannot resolve constructor.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Yan Khonski
  • 12,225
  • 15
  • 76
  • 114
  • http://stackoverflow.com/questions/29835382/use-method-reference-with-parameter or http://stackoverflow.com/questions/31251629/java-8-supplier-with-arguments-in-the-constructor – Tom Feb 09 '17 at 12:14

1 Answers1

9

Use a Supplier:

.orElseGet(() -> new Employee( 1L, "", ""));

FYI, an Employee instance will only be created when it's actually needed.


If your constructor had no args, you could have used a method reference Employee::new. You could still use a method reference if you create a factory method:

class Employee {
    // rest of class
    public static Employee createDummy() {
        return new Employee( 1L, "", "");
    }
}

then you could:

.orElseGet(Employee::createDummy);

The factory method could actually be in any class as you like.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • The factory method is a static one, right? – Yan Khonski Feb 09 '17 at 12:24
  • @Jan it doesn't have to be, but if it's not you need an instance of a factory, which you can still use a method reference with: `class Factory { Employee createDumy() {...}}` then `Factory f = new Factory();` (which can be an instance variable or whatever) and `.orElseGet(f::createDummy)`. I think static factory methods are simpler to use and code because you don't need an instance. But there are times when you want to pass a factory to some code that needs a way to create an instance provided to it. For example, your method could accept such a supplier as an argument – Bohemian Feb 09 '17 at 12:27