Call Multiple Methods on one Line?

17,498

Solution 1

It looks like you're trying to be too succinct and in the process possibly shooting yourself in the foot. You don't need to know the ArrayList index to set up the Fireball object that you're adding. You just need to have a reference to the object, and you can easily do that by creating a local Fireball variable, setting it up, and then adding it to the ArrayList.

Why not simply do:

Fireball fireball = new Fireball(tileMap);
fireball.setPosition(20, 20);
fireball.setLeft();
fireBalls.add(fireball);

Solution 2

You can modify your Fireball methods, so they return an instance of that class (in other words return this;)

public Fireball setPosition(int x, int y) {
    ...
    return this;
}

With this, the call to

new Fireball(tileMap).setPosition(20, 20)

will return the recent created instance, so you can call setLeft() from that instance. You could implement this for setLeft() too.

public Fireball setLeft() {
    ...
    return this;
}

Solution 3

To do that, your Fireball class should follow builder pattern, which methods return the instance itself. So, you can can chain the method in a line.

For example method : java.lang.StringBuilder#append()

Solution 4

While I believe Hovercraft's answer is the best by far, an alternative solution might be to write a better constructor.

A constructor that takes a tileMap (whatever this is), two ints for setting position, as well as a boolean or enum or something appropriate for whatever setLeft() does could be used here.

fireballs.add(new Fireball(tileMap, 20, 20, true));
Share:
17,498
sparklyllama
Author by

sparklyllama

Updated on June 16, 2022

Comments

  • sparklyllama
    sparklyllama almost 2 years

    If I have a line like this in my program:

    fireBalls.add(new Fireball(tileMap).setPosition(20, 20)); // set position is a method of the fireball class 
    

    How can I call multiple methods like that, on that same line?

    I tried this:

    fireBalls.add(new Fireball(tileMap).setPosition(20, 20).setLeft());
    

    But the setLeft() method can't be put there, as it can't be called on a void type. I can't have them on separate lines, as I don't know what index it would be in the fireBalls ArrayList.

  • sparklyllama
    sparklyllama over 10 years
    This is a great alternative to what other people have be suggesting. Thank you for helping! +1
  • nhgrif
    nhgrif over 10 years
    The accepted answer should be changed to this one in my opinion.
  • Michael Laffargue
    Michael Laffargue over 2 years
    For reference purpose : en.wikipedia.org/wiki/Method_chaining