Let's taken some simple example code:
Employee employee = repository.findById(id).orElseThrow(() -> new EmployeeNotFoundException(id));
From my understanding, the lambda is used to create a subistute of a functional interface (only 1 method), and empty parenthesis means that the method has no parameters.
But what method is called in orElseThrow that a lambda is needed? I thought it is either an Optional
or an Exception
.
So my question is: How would this look like without a lambda call?
Employee class:
class Employee {
private Long id;
private String name;
private String role;
Employee() {}
Employee(String name, String role) {
this.name = name;
this.role = role;
}
}
and the exception class:
class EmployeeNotFoundException extends RuntimeException {
EmployeeNotFoundException(Long id) {
super("Could not find employee " + id);
}
}
EDIT: I am interested in how to write a valid, compilable substitution for the lambda- expression. Right now I am at
Employee employee = repository.findById(id).orElseThrow(
new Supplier<Throwable>() {
@Override
public Throwable get() {
return new EmployeeNotFoundException(id);
}
}
)
but that is not right, since now I would need to add the exception to the method signature, which is not the case when using the lambda..it shows that I don't know how to implement the supplier class by hand instead of just skipping all that by the use of lambdas