blog rss feed

Groovy part 2 - focusing on the language

Keywords:

Last editor: Dave Cherry, last modified: Aug 3, 2008

Expando's - how to build an object on the fly.

An Expando is an object shell that can be built up. Although this is an odd comparison, I think of it a little like Mr Potato Head, you can stick whatever bits onto it that you like. Every time you set a property on an Expando, it is remembered and can be recalled later. This is an incredibly powerful concept, an example may help:

import java.util.regex.Matcher

def exp = new Expando();

// here we define the properties of the expando
exp.name = "Dave";
exp.title =
"Mr";
exp.employeeNumber =
2;
exp.salary =
50.0;

// here we access the properties directly
println("name: ${exp.title} ${exp.name} (${exp.employeeNumber}).")

// here we find out what properties are available
println("Expando contains ${exp.properties}")

Regular expressions (or regex)

If you've not come across regular expressions before, then I would start with a good book on the subject, or an internet guide such as http://www.regular-expressions.info/ will be most helpful.

Groovy has Regular Expression (regex) support built directly into the language, supporting a much more natural syntax than is available in java. In fact groovy has operators devoted just to regular expressions. Also, the more standard expression in forward slashes is supported (/expression/ ); which as an added benefit does not process the \ escape character. Lets take a look:

// ==~ is match exactly the expression (dog or dogs)
assert( 'dog' ==~ /dogs?/)

// =~ is a match within the string
assert( 'dogs and cats' =~ /dogs?/)

// =~ actually returns a matcher that we can use
Matcher matcher = 'dogs and cats' =~ '(dog)|(cat)'
while(matcher.find())
{
println(
"match: ${matcher.group()}");
}

Further reading

I hope these two starter articles have been helpful getting you started with Groovy, there's quite a few other articles on our site; which are all free and allow user comments, in addition we welcome your feedback. However, these starter guides are no replacement for a good book on the subject, of which several are available. Also, see the good quality reference guides on the groovy website.

<< 1 2 3

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30