Library contents

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

  1. Start with 1, 2, 3
  2. Do this Start at 0 and add each value
  3. Result 6
The running total changes from 0 to 1, then 3, then 6.

Syntax

Groovy 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.

First output line425
Lesson.groovy
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([])
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result14

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?

Given3 · 0 · 8 · 3
Worked result14