简体   繁体   English

Groovy范围,变量分配和引用

[英]Groovy scope, assignment, and reference of variables

I would like help understanding how Groovy manages scope and variables when passed between functions. 我想帮助您了解Groovy在函数之间传递时如何管理范围和变量。 Say I declare def foo in my main method and pass it as an argument to a private void method, changeStuff. 假设我在main方法中声明def foo并将其作为参数传递给私有void方法changeStuff。 Then I can make changes like follows: 然后,我可以进行如下更改:

public static void main(args) {
  def foo = [:];
  changeStuff(foo);
  println(foo);
}
private static void changeStuff(foo) {
  foo.bar = "new stuff";
}

The result printed is [bar:new stuff] But I have a hard time manipulating foo in other ways. 打印的结果是[bar:new stuff]但是我很难用其他方式来操纵foo。 See these next two examples: 请参阅以下两个示例:

public static void main(args) {
  def foo = [:];
  changeStuff(foo);
  println(foo);
}
private static void changeStuff(foo) {
  def newStuff = [:]
  newStuff.extra = "extra stuff";
  foo = newStuff;
}

prints: [:] 打印: [:]

public static void main(args) {
  def foo = "before";
  changeStuff(foo);
  println(foo);
}
private static void changeStuff(foo) {
  foo = "after";
}

prints before before打印

I know there is some concept here that I am not fully understanding, maybe related to def ? 我知道这里有些我不完全了解的概念,也许与def有关? Any summary or direction on where I can learn more about this is appreciated. 我可以在其中获得更多了解的任何摘要或方向。

My experience in groovy is very limited, so I might be off a bit. 我在groovy方面的经验非常有限,因此我可能会感到有些不适。

In the first case you mention, you are passing foo by reference to changeStuff , and inside the method, you directly modify the map, so changes are visible from your main method. 在您提到的第一种情况下,您通过引用将foo传递给changeStuff ,并且在方法内部直接修改了映射,因此可以从main方法中看到更改。

In the second case, the parameter foo inside your changeStuff method is being assigned to another map. 在第二种情况下, changeStuff方法中的参数foo被分配给另一个映射。 However, the variable foo inside your main method still points to the first map you have created, thus the empty map when you print it. 但是, main方法中的变量foo仍指向您创建的第一个地图,因此在打印时为空。

The third case is the same as the second case. 第三种情况与第二种情况相同。 Plus, you have to be aware that String objects in Java (and probably in Groovy too) are immutable. 另外,您必须意识到Java(可能还有Groovy)中的String对象是不可变的。 So when "modifying" a String , what you are really doing is creating a new instance each time. 因此,当“修改”一个String ,您真正要做的就是每次创建一个新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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