سؤال

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));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top