Learn/Groovy/6. Methods and closures
Lesson 6 of 8
Sign in

Groovy, lesson 6

Methods and closures

As programs grow, you want to name a piece of work and reuse it. Groovy gives you two tools: methods, which are named and declared at the top level, and closures, which are blocks of code you can store in variables and pass around.

Methods

A method has a name, a list of parameters and a body:

You can declare the return and parameter types (int square(int x)) or use def for either. Types make the method's contract clear and catch wrong arguments early.

The return keyword is optional: a method returns the value of its last expression, as area does. Use return explicitly when it makes the code clearer, especially for an early exit from the middle of a method.

A method that only does something, like printing, has the return type void:

2 exercises to try what you just read.

Exercise 1

Shipping cost

Press Ctrl Enter or Check to test your code.

Exercise 2

Letter grades

Press Ctrl Enter or Check to test your code.

In a script, you may call a method before or after its definition in the file; Groovy compiles the whole script first.

Default arguments

A parameter can have a default value, used when the caller leaves it out:

Closures

A closure is a block of code in braces that you can store in a variable and call later. Parameters come before an arrow:

If a closure has a single parameter, you can skip it and use the implicit name it: def twice = { it * 2 }. Closures are the reason Groovy code like list.each { println it } works: each is a method whose argument is a closure. When the closure is the last argument, it can go outside the parentheses.

Scope

Parameters and variables declared inside a method exist only in that method. Two methods can both have a parameter called x without clashing.

There is one Groovy quirk to know. In a script, a variable declared with def or a type at the top level is a local variable of the script, so methods cannot see it:

The cure is simple: pass what a method needs as parameters. Closures are different: a closure can use the variables around the place where it was written, which is exactly what makes them handy for short pieces of logic.

Further reading

  • Object orientation: methods and default arguments
  • Closures
  • Program structure: script variables

A courier charges 5 for a parcel of up to 1 kg, plus 2 for every kilogram above that. Write the method shipping(int weight) that returns the cost for a whole number of kilograms (at least 1).

The starter reads one line of weights separated by spaces and prints the cost of each, one per line. You only need to fill in shipping.

Sample input:

Sample output:

Write a method grade(int score) that turns a score from 0 to 100 into a letter: 90 or more is A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.

The starter reads scores, one per line, and prints each score with its letter. Fill in grade.

Sample input:

Sample output:

int square(int x) {
    return x * x
}

def area(width, height) {
    width * height
}

println square(7)          // 49
println area(3, 4)         // 12
void greet(String name) {
    println "Welcome, ${name}!"
}
String greeting(String name = "friend") {
    "Hello, ${name}!"
}

println greeting()          // Hello, friend!
println greeting("Ada")     // Hello, Ada!
def twice = { n -> n * 2 }
def add = { a, b -> a + b }

println twice(21)          // 42
println add(2, 3)          // 5
def taxRate = 5
int withTax(int price) {
    price + taxRate          // error at run time: taxRate is not visible here
}
1 3 10
5
9
23
95
72
40
95 A
72 C
40 F