Example
This test fails because each
does not modify the list's elements.
void test_each_DoesNotModifyListElements() {
List<String> list = ["a", "b", "c"]
list.each { it = it + "z" }
assert ["az", "bz", "cz"] == list
}
This test passes because collect
returns a new list with modified elements.
void test_collect_ReturnsNewListWithModifiedElements() {
List<String> list = ["a", "b", "c"]
list = list.collect{ it + "z" }
assert ["az", "bz", "cz"] == list
}
Assumption
At this point, I am assuming that each
does not modify the list's elements because I have written the tests below and I am assuming that that's what the tests are telling me. Please correct me if I am wrong.
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
}
Question
So the question is: as a Groovy beginner, how should I have known beforehand, meaning before writing tests and googling, that each
does not change the list's element?
By reading the documentation?
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.
Oftentimes, I end up spending a lot of time trying things out and googling for answers. Shouldn't there be a more efficient way? Is there?