Groovy inject
inject folds a collection into an accumulator. Providing an explicit initial value also defines the result of an empty invoice.
A simple example
inject
- Start with 1, 2, 3
- Do this Start at 0 and add each value
- Result 6
Syntax
rows.inject(initial) { total, row -> nextTotal }
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Accumulate an invoice in integer cents
An invoice printer must turn line prices into a reproducible money total. Decide where rounding happens and which unit the accumulator stores before comparing the printed invoice with the ledger.
def total = { rows ->
rows.inject(0L) { cents, row -> cents + row.price * row.qty }
}
println total([[price: 150L, qty: 2], [price: 125L, qty: 1]])
println total([])
425 0
Each row contributes its unit price times its quantity. The long seed preserves the chosen integer representation even when there are no rows.
Groovy documentation for inject
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The shift total is the sum of the listed counts. What total goes on the handover slip?
Review print quantities
A print room records four job quantities, including a cancelled job. The shift total is the sum of the listed counts. What total goes on the handover slip?