简体   繁体   English

java-调用void方法,然后将对象传递到一行

[英]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? 是否可以传递一个对象但先在同一行中对该对象调用void方法? 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; 我使用的是来自第三方API的Vector对象,它仅保存3个坐标,并将其传递给组合的setLocation(Vector)方法; but first I want to add 3 to the Y value of that Vector which is done by Vector#addY(3f); 但是首先我想在Vector的Y值上加上3,这是通过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. 如果您可以将addY()更改为“ return this”,那么您就是在做生意。

Since it is a third party API maybe you just need a helper function: 由于它是第三方API,也许您只需要一个辅助函数:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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