Database Reference
In-Depth Information
db.setApplication( "Sample")
// calls the automatic setter
db.name = "Basic"
// also calls the automatic setter
println db.application + '.'
+ db.getName()
// both call the automatic getter
These features make it easier to work with classes created by others and to create
new custom classes. As a side note, these features also make it simple to build and work
with Java “beans,” although that subject is outside the scope of this chapter. The main
thing to know is that groovy lets you work with objects and their properties the way
you want to.
9.4.9 GStrings
Another feature mentioned in a previous sidebar (Section 9.3.2) is gStrings. They are a
way to build strings out of different values and literals at runtime.
funFact = "My favorite Essbase database is ${db.application}.${db.
name}."
println funFact // prints My favorite Essbase database is Sample.
Basic.
This convenience feature makes string construction much easier to write and to read.
most particularly, it relieves the burden of having to add spaces at the beginning or end
of the string snippets that are being added together.
It is important to understand that gStrings are not like functions. They do not change
once they have been evaluated, as demonstrated below.
timeStamp = "It is now ${new Date()}"
println timestamp // prints the current time, down to the second
sleep(10000) // waits 10 seconds
println timeStamp // prints the same time as before, down to the
second
2.times {
println "It is now ${new Date()}" // prints a different time
each iteration
sleep(10000)
}
In the first part, the gString is not re-evaluated. It is just reprinted. In the second
part, the gString is re-evaluated because the closure is executed two separate times.
9.4.10 Regular Expressions
Java provides a library that allows very nifty and powerful pattern-based searching and
matching for strings. groovy integrates this library at the language level. The technology
is called “regular expressions,” and it is provided by the package java.util.regex. regular
expressions (“regexes”) provide an extremely versatile method for defining and look-
ing for potentially complex patterns of characters within strings. This is an exceedingly
common programming task, and once regexes are learned, many developers find them
indispensable. We can use them to verify properly formatted email addresses, work
intelligently with phone numbers in varied input formats, split names up into their
Search WWH ::




Custom Search