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.
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);
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;
}
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