How to instantiante object & call setter on same line?

Viewed 19242

If I have an Employee class with a default constructor:

private String firstName;
public Employee(){}

and a setter:

public void setFirstName(String firstName){
    this.firstName = firstName;
}

Why does this attempt fail to instantiate and call the setter in the same line?

Employee employee = new Employee().setFirstName("John");
8 Answers

In order for your code to work, you would have to return the Employee (meaning "this") in the setter method setFirstName.

If you don't own the Employee class (I know this is just a simple example - but for the sake of argument) and cannot modify it, one way to solve that is using functional programming. You could declare yourself a function like this:

static final Function<String, Employee> EMPLOYEE = firstName -> {
        Employee employee = new Employee();
        employee.setFirstName(firstName);
        return employee;
};

And then you can create your employee in one line like this:

Employee jake = EMPLOYEE.apply("Jake");

Maybe not exactly what you want, but still useful.

Related