It applies an operation to a collection and keeps track of an intermediate value. Take this example: [1, 2, 3, 4].inject(0, { sum, value -> sum + value })
. This says use 0 as the initial value and apply the addition operation to the intermediate result and each element in sequence. Each application of the operation generates a new intermediate result. In this case, the closure adds up the numbers, so it generates the sum of the list. You can imagine it like:
<initial value> <operation> <element1> <operation> ... <elementn>
Or, in the case of [1, 2, 3, 4].inject(0, { sum, value -> sum + value })
:
0 + 1 + 2 + 3 + 4
To find the product of a list, you can use [1, 2, 3, 4].inject(1, { product, value -> product * value})
. In this case, 1 is used as the initial value, since it is the identity value for mulitplication.
Here's an example that splits a list of multi-word strings into a flat list of words:
strings = ["", "this", "is a", "test of inject!"]
words = strings.inject([], { list, value -> list + value.tokenize() })
assert words == ["this", "is", "a", "test", "of", "inject!"]
Other terms that are sometimes used to describe this operation are "reduce", as in MapReduce, or a "fold" (specifically a foldl).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…