-1

the bottom member method has a consecutive use of the "." operator to call member "set" methods as a way to return an object

I haven't encountered this syntax before is this valid Java syntax? what is this chaining called (how can I lookup such syntax usage?)?

public class OrderItemModel {
    private String restaurantId;
    private String restaurantName;
    private List<FoodModel> foods;
    private List<Long> numOfFoods;

    private OrderItemModel() {}

. . .

    public static OrderItemModel buildAdditional(ShoppingCartModel shoppingCart) {
        return new OrderItemModel().
        setRestaturantId(shoppingCart.getAdditionalRestaurantID()).
        setRestaurntName(shoppingCart.getAdditionalRestaurantName()).
        setFoods(shoppingCart.getAdditionalFoods()).
        setNumOfFoods(shoppingCart.getNumOfAdditionalFood());
    }
Dror
  • 5,107
  • 3
  • 27
  • 45
  • Builder pattern. – Johannes Kuhn Nov 01 '18 at 19:20
  • It is method chaining. It constructs a new object, calls a method on the object, calls a method what the first method returns, etc, etc – GBlodgett Nov 01 '18 at 19:20
  • Two notes: When chaining on multiple lines like this it's customary to indent and to put the dot on at the beginning of the line to make it clear to a reader that it's a continuation of the statement, and for better or for worse standard JavaBean setters are void (not returning `this`), so this style is normally only seen in builders. – chrylis -cautiouslyoptimistic- Nov 01 '18 at 19:22

1 Answers1

0

This is possible with methods like this, which return an instance of the class when they're called:

class Person {

    public Person setName(String a) {

        return this;
    }

    public Person setAge(int age) {

        return this;
    }

}

And using it like so:

Person person = new Person();
person.setName("abc").setAge(19);

The reason this is possible is you have variable person, you set the name using setName but setName returns an instance of that class, therefore you can call setAge on that instance that was returned etc. It's not called a 'dot operator' it's just chaining method calls.

Mark
  • 5,089
  • 2
  • 20
  • 31