Listing 22-3. Dynamic Typing in Groovy
package com.apress.prospring3.ch22.groovy
class Contact {
def firstName
def lastName
def birthDate
String toString() { "($firstName,$lastName,$birthDate)" }
}
Contact contact = new Contact(firstName: 'Clarence', lastName: 'Ho', birthDate: new Date())
Contact anotherContact = new Contact(firstName: 20, lastName: 'Ho', birthDate: new Date())
println contact
println anotherContact
println contact.firstName + 20
println anotherContact.firstName + 20
Listing 22-3 shows a Groovy script, which can be run directly from within STS (right-click the file
and choose Run As, and then choose either Groovy Script or Java Application). The main difference is
that a Groovy script can be executed without compilation (Groovy provides a command-line tool called
groovy that can execute Groovy scripts directly) or can be compiled to Java bytecode and then executed
just like other Java classes. Groovy scripts don't require a main() method for execution. Also, a class
declaration that matches the file name is not required.
In Listing 22-3, a class Contact is defined, with the properties set to dynamic typing with the def
keyword. Three properties are declared. Then, the toString() method is overridden with a closure that
returns a string.
Then, two instances of the Contact object are constructed, with shorthand syntax provided by
Groovy to define the properties. For the first Contact object, the firstName attribute is supplied with a
String, while an integer is provided for the second Contact object. Finally, the println statement (the
same as calling System.out.println() method) is used for printing the two contact objects. To show how
Groovy handles dynamic typing, two println statements are defined to print the output for the
operation firstName + 20. Note that in Groovy, when passing an argument to a method, the parentheses
are optional.
Running the program will produce the following output:
(Clarence,Ho,Mon Jan 16 17:14:50 CST 2012)
(20,Ho,Mon Jan 16 17:14:50 CST 2012)
Clarence20
40
From the output, you can see that since the firstName is defined with dynamic typing, the object
constructs successfully when passing in either a String or an integer as the type. In addition, in the last
two println statements, the add operation was correctly applied to the firstName property of both
objects. In the first scenario, since firstName is a String, the string 20 is appended to it. For the second
scenario, since firstName is an integer, integer 20 is added to it, resulting in 40.
Dynamic typing support of Groovy provides greater flexibility for manipulating class properties and
variables in application logic.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home