简体   繁体   中英

java - call a void method then pass the object on one line

Here is something I've been wanting to know for a long time now.

Is it possible to pass an object but first call a void method on that object in the same line? It is quite hard to explain but I'll give an example:

I'm using a Vector object from a third party API, it just holds 3 coordinates, and I'm passing it into a made up setLocation(Vector) method; but first I want to add 3 to the Y value of that Vector which is done by Vector#addY(3f); So is it possible to do this on the same line?

setLocation(new Vector(0f,4f,0f).addY(3));

I think that should explain what I mean.

If you can change addY() to "return this" then you're in business.

Since it is a third party API maybe you just need a helper function:

Vector makeAndSetupVector(float f1, float f2, float f3, int y) {
   Vector vect = new Vector(f1, f2, f3);
   vect.addY(y);

   return vect;
}

Now you can do:

setLocation(makeAndSetupVector(0f, 4f, 0f, 3));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM