|
Helping ordinary people create extraordinary websites! |
Practically Groovy: Go Server-Side Up, with GroovyBy Andrew Glover2005-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){
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){
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 |
|