Groovy — Methods, parameters, and implicit returns
A Groovy method can return the value of its last expression. Typed integer parameters and an int result describe the calculation that callers can reuse.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
int twice(int n) {
return n + n
}
println(twice(2))
4
Calculate how many boxes an order needs
The last expression in the method supplies its return value. The explicit int parameter and return types describe the interface. The intdiv call avoids fractional division.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
int boxesNeeded(int items, int capacity) {
items.intdiv(capacity) + (items % capacity == 0 ? 0 : 1)
}
println boxesNeeded(17, 8)
println boxesNeeded(16, 8)
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.