0

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
werter318
  • 55
  • 1
  • 8
  • 7
    No, unless the `addY` method returns a new `Vector` object, which is not your case – BackSlash Jan 19 '14 at 10:33
  • System.out.println(new ArrayList().add("5")); prints true because add returns boolean value.. So, you can call a method only when the entire chain of methods returns your object otherwise, it makes no sense.. – TheLostMind Jan 19 '14 at 10:34
  • 5
    A seperate question is why would you want to? Pushing several actions onto a single line is the best way to reduce code clarity – Richard Tingle Jan 19 '14 at 10:34
  • Ok, thank you! I just wanted to know if it was possible. – werter318 Jan 19 '14 at 10:34
  • 1
    This setup is what's known as a "fluent API". Unfortunately, the JavaBeans standard baked in that setters return `void` instead of `this`, so you usually can't. – chrylis -cautiouslyoptimistic- Jan 19 '14 at 10:37
  • This all depends on how the API has been designed. If `addY` returns `this`, then the answer is yes. Otherwise no. But as Richard Tingle said - why do this? – Dawood ibn Kareem Jan 19 '14 at 10:39
  • A question regarding the pros and cons of returning 'this' instead of void was asked here; http://stackoverflow.com/questions/16976150/benefits-and-drawbacks-of-method-chaining-and-a-possibility-to-replace-all-void – Richard Tingle Jan 19 '14 at 10:39
  • As I said, I just wanted to know if it was possible. Believe it or not I am actually a pretty experienced java developer :). – werter318 Jan 19 '14 at 10:42

1 Answers1

5

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));
MikeHelland
  • 1,151
  • 1
  • 7
  • 17