55. The Basics
Let’s start by examining a new method we’ll write to calculate the average of the numbers in a list:
def determineAverage(list) {
return list.sum() / list.size()
}
Breaking that code up we can see:
- The
defreserved word is used to commence the method declaration- Much like we use when defining a variable
-
determineAverageis the name of the method - The method accepts a single parameter,
list - A single value is returned using the
returnreserved word- In this case it’s the result of
list.sum() / list.size()
- In this case it’s the result of
The method name (determineAverage) may look a bit odd but it uses a naming strategy called “lower Camel Case”. The camel aspect is the use of upper-case letters to indicate individual words in the name (hence Average). The first word in the method name is a verb (determine) to indicate that a method “does” something.
Let’s return to that determineAverage method and get a complete script together - you can copy and paste this into groovyConsole and run it to experience the method first-hand:
def determineAverage(list) {
return list.sum() / list.size()
}
def scores = [2, 7, 4, 3]
def result = determineAverage(scores)
println result
Let’s look at the main components of that script:
- The
determineAveragemethod is defined as before- This can appear above or below the other code
- A new list of numbers is created:
def scores = [2, 7, 4, 3] - The method is called with the
scoresvariable passed as a parameter - The return value (result) of
determineAverageis stored in theresultvariable.
In the example I called the method using determineAverage(scores) but, in many cases, I don’t need to use the parentheses and determineAverage scores would have also worked. That’s why println 'hello, world' works just fine. This works really well when you start to use Groovy to construct domain-specific languages.