gpt4 book ai didi

groovy - 我应该如何确定 Groovy 的 each() 不会更改列表的元素?

转载 作者:行者123 更新时间:2023-12-04 16:36:21 27 4
gpt4 key购买 nike

示例

此测试失败,因为 each 没有修改列表的元素。

void test_each_DoesNotModifyListElements() {
List<String> list = ["a", "b", "c"]
list.each { it = it + "z" }
assert ["az", "bz", "cz"] == list
}

此测试通过,因为 collect 返回一个包含已修改元素的新列表。

void test_collect_ReturnsNewListWithModifiedElements() {
List<String> list = ["a", "b", "c"]
list = list.collect{ it + "z" }
assert ["az", "bz", "cz"] == list
}

假设

在这一点上,我假设 each 不会修改列表的元素,因为我已经编写了下面的测试并且我假设这就是测试告诉我的内容。如果我错了,请纠正我。

void test_each_DoesNotModifyListElements1() {
List<String> list = ["a", "b", "c"]
list.each { it + "z" }
assert ["az", "bz", "cz"] == list
}

void test_each_DoesNotModifyListElements2() {
List<String> list = ["a", "b", "c"]
list.each { it = it + "z" }
assert ["az", "bz", "cz"] == list
}

void test_each_DoesNotModifyListElements3() {
List<String> list = ["a", "b", "c"]
list = list.each { it = it + "z" }
assert ["az", "bz", "cz"] == list
}

问题

所以问题是:作为一个 Groovy 初学者,我应该如何事先知道,意思是在编写测​​试和 googling 之前, each 不会改变列表的元素吗?

通过阅读文档?

Groovy each documentation: Iterates through an aggregate type or data structure, passing each item to the given closure. Custom types may utilize this method by simply providing an "iterator()" method. The items returned from the resulting iterator will be passed to the closure.

通常,我最终会花费大量时间来尝试并在谷歌上搜索答案。难道不应该有更有效的方法吗?有吗?

最佳答案

嗯,这与 Java/Groovy 编程基础知识相差无几。有对象,也有变量。变量可以持有指向对象的“链接”,称为引用。所以基本上,您可以使用变量访问存储在计算机内存深处的真实对象。

无论何时您更改变量(即向其分配某些内容),您永远不会修改真实对象。相反,变量开始指向一些不同的对象。

现在,再次查看文档:

Iterates through an aggregate type or data structure, passing each item to the given closure.

这就是它所做的一切。它为您提供了一个指向每个项目的变量。如果你覆盖了给定的局部变量,变量开始指向其他对象,仅此而已。该列表仍然具有对旧对象的引用。

该信息是使用 Java 和类似语言进行编程所需的最基本知识。通常它会在手册/文档的第一页进行解释。因为它是如此基础,所以没有人会为每个具有某种参数的函数一遍又一遍地解释它。

关于groovy - 我应该如何确定 Groovy 的 each() 不会更改列表的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16438273/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com