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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With