Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Practically Groovy: Go Server-Side Up, with Groovy

By Andrew Glover
2005-05-05


Defining Functions in Scripts

In normal Java programming, methods must exist within a class object. In fact, all behavior must be defined within the context of a class. In Groovy, however, behavior can be defined within functions, which can be defined outside a class definition.

These functions can be referenced directly by name and can be defined in Groovy scripts, where they can seriously facilitate reuse. Groovy functions require the def keyword, and you can think of them as globally static methods available within a script's scope. Because Groovy is a dynamically typed language, defs do not require any type declarations for parameters, nor do defs require a return statement.

For example, in Listing 1, I define a simple function that prints out the contents of a collection, be it a list or a map. I then proceed to define a list, populate it, and call my newly defined def. Next, I create a map and do the same thing for that collection.

Listing 1. Now that's def!

def logCollection(coll){

counter = 0;
coll.each{ x |
println "${++counter} item: ${x}"
}
}
lst = [12, 3, "Andy", 'c']
logCollection(lst)
mp = ["name" : "Groovy", "date" : new Date()]
logCollection(mp)
defs do not require a return statement, so if the last line produces some value, that value is returned by the def. For example, in Listing 2, the code defines a def that returns the class name of the variable passed in. I can write it with or without the return statement, and my results will be the same.

Listing 2. Return statements are optional in defs

def getJavaType(val){

val.class.getName()
}
tst = "Test"
println getJavaType(tst)
The def keyword can be extremely handy when it comes to writing simple scripts. As you'll soon see, it can also be useful when developing Groovlets.

Tutorial Pages:
» On-the-fly Server-Side Programming with Groovlets and GSPs
» Defining Functions in Scripts
» Groovlets and GSPs
» The Groovlet, Please
» A Diagnostic Groovlet
» What About Those GSPs?
» Refactor me this ...
» Conclusion
» Resources


First published by IBM DeveloperWorks


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources