So I'm writing my version of Tetris. Here's what I'd like to do:
screen[0][1].setColor(Color.RED);
screen[0][1].setStatus(1);
Is there a way to do this in only one line?
So I'm writing my version of Tetris. Here's what I'd like to do:
screen[0][1].setColor(Color.RED);
screen[0][1].setStatus(1);
Is there a way to do this in only one line?
A few options spring to mind:
Write a method in whatever class this is which knows about both the status and the color:
// Implicitly sets color to red. Consider using an enum for statuses
screen[0][1].setStatus(1);
Write a method accepting both state and color parameters:
screen[0][1].setColorAndStatus(Color.RED, 1);
Make setColor
and setStatus
(and other setters) return this
so you can chain them:
screen[0][1].setColor(Color.RED).setStatus(1);
Abandon the "all in one statement" idea (which is what I think you really meant - you can put two statements on one line if you really want, but I'm not suggesting that you do) and actually write three statements:
Tile tile = screen[0][1];
tile.setColor(Color.RED);
tile.setStatus(1);
Just for the same of accomplishing this, you could change methods setColor()
and setStatus()
to return this
. Something like:
public MyObj setColor(int color) {
this.color = color;
return this;
}
But I wouldn't do this, it doesn't seem like a good pattern, unless other methods follow the same approach.
Direct possibilities.
if setColor method returning the object of type screen[0][1]
then you can do
screen[0][1].setColor(Color.RED).setStatus(1);
if setColor method return type is void. Then only way is
screen[0][1].setColor(Color.RED);
screen[0][1].setStatus(1);
If you are able to edit the class , there are many other ways we have here so far :)
The possible method can be anyone given by others :
also try it
(screen[0][1].setColor(Color.RED)).setStatus(1);