Introduction To Groovy Programming Language
Introduction to groovy
Groovy is an object-oriented programming language which could be described as Java paired with a dynamic scripting language like JavaScript or Python.
You can use Groovy in two different "modes":
You can compile Groovy to JVM Bytecode like Java. That way you just need to package it with the groovy library and it can run in the JVM like Java can. You can use your build system (e.g. the Groovy Gradle plugin) to use and build Groovy in your regular projects.
It is a dynamic language similar to Python, Ruby and Perl.
They do little or no checking for the existence of methods at compile time but instead do it all at runtime. This means that it supports many cool syntax and features that makes working with Groovy so much nicer than working with plain Java.
It is compiled to Java bytecode. This means you can run Groovy programs in any Java Virtual Machine. Similarly, Grails projects that are written in Groovy, can be deployed to Java application servers such as Tomcat, JBoss, GlassFish, and others
Groovy is an object-oriented programming language which could be described as Java paired with a dynamic scripting language like JavaScript or Python.
You can use Groovy in two different "modes":
You can compile Groovy to JVM Bytecode like Java. That way you just need to package it with the groovy library and it can run in the JVM like Java can. You can use your build system (e.g. the Groovy Gradle plugin) to use and build Groovy in your regular projects.
You can use it as a scripting language. Just write your Groovy code inside a file and execute this file by calling (once you have Groovy installed):
$ groovy your-script.groovy
It is a superset of Java.
This means any valid Java code is a valid Groovy code also. If you
don't like using Groovy, you can use plain Java syntax when working with
Grails.It is a dynamic language similar to Python, Ruby and Perl.
They do little or no checking for the existence of methods at compile time but instead do it all at runtime. This means that it supports many cool syntax and features that makes working with Groovy so much nicer than working with plain Java.
It is compiled to Java bytecode. This means you can run Groovy programs in any Java Virtual Machine. Similarly, Grails projects that are written in Groovy, can be deployed to Java application servers such as Tomcat, JBoss, GlassFish, and others
Creating a Groovy Project
To play with Groovy, we need to have a Groovy project to work with.
Start your Groovy/Grails Tool Suite IDE
File > New > Project > Groovy Project >click next > Give it a project name “testGroovyProject”
Use an execution environment jre - Java SE1.6
Create separate folders for sources and class files
Creating a Groovy Class
File > New > Groovy Class
Specify your desired class name. For example TestProgram:
Source folder – com/src
Package – com
And it will generate a file like this:
Create this program
package com
class TestProgram{
static void main(args){
println “Hello World”
}
}
Run the class as Groovy Script. This will display the output Hello World in the console
Weak Typing
An important thing to note in Groovy is that it is not a strong typed language. The following are valid:
static void main(args){
def a = 'John Doe'
a = new Object()
a = 10 println a
}
And will print 10 to the console.
Use of def
Typing information is also optional; instead of specifying a type, you can just use the keyword def, as shown in Listing
Use of def is mandatory for methods, but it is optional for parameters on those methods. You should also use def for
class and method variables. While we're at it, let's take out those semicolons; they're optional in Groovy.
class Hello {
def sayHello(name) {
println("Hello $name!")
}
static def main(args) {
Hello hello = new Hello()
def name = 'world'
hello.sayHello(name)
}
}
When we declare a variable or function in Groovy, we can use the def keyword to define the type.
The Groovy Def can be used if we don't want to restrict the type of an object. Hence, we can change what can be assigned to a variable any time during runtime. When we use Groovy def to declare something, it is similar to declaring it as an Object class. Because the class Object is the root class of all classes, you can assign anything to a variable of type Object. Here are some examples on how to use def in Groovy
Groovy Def Variables
We can NOT do this in Java or Groovy.
String myvar = 'Test'
myvar = 1000
This will throw a Runtime Exception because the code is trying to assign an integer to a String variable.
We can use def to declare the type of a variable. And we can assign anything to it.
def myvar = 'Test'
myvar = 1000
This code will not throw Exception. The code above is similar to the one below:
Object myvar = 'Test'
myvar = 1000
As previously stated, using def is like declaring the variable to have the type Object.
Class Numeric
Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed −
We can NOT do this in Java or Groovy.
String myvar = 'Test'
myvar = 1000
This will throw a Runtime Exception because the code is trying to assign an integer to a String variable.
We can use def to declare the type of a variable. And we can assign anything to it.
def myvar = 'Test'
myvar = 1000
This code will not throw Exception. The code above is similar to the one below:
Object myvar = 'Test'
myvar = 1000
As previously stated, using def is like declaring the variable to have the type Object.
Groovy Def Function/Method
When we declare the return type as def, it means the method can return any type of object.
class DefExample {
public static def foo(int i) {
if ( i < 100 ) {
return -1
}
return 'Hello World'
}
static void main(String[] args) {
println foo(50)
println foo(200)
}
}
public static def foo(int i) {
if ( i < 100 ) {
return -1
}
return 'Hello World'
}
static void main(String[] args) {
println foo(50)
println foo(200)
}
}
String
Note this example:
static void main(args){
def firstName = 'John'
def lastName = 'Doe'
def a = 3
def b = 7
println "${lastName}, ${firstName}"
println "a + b = ${a + b}"
println '${lastName}, ${firstName}'
println 'a + b = ${a + b}'
}
static void main(args){
def firstName = 'John'
def lastName = 'Doe'
def a = 3
def b = 7
println "${lastName}, ${firstName}"
println "a + b = ${a + b}"
println '${lastName}, ${firstName}'
println 'a + b = ${a + b}'
}
Using an Array
This is one place where Java syntax differs from Groovy's. To create a static array, you'd instead do this:
def sayHello(name) {
println("Hello $name!") }
String[] names = ["SintSi", "Kaitlyn", "Keira"]
for (name in names) {
sayHello(name)
}
def sayHello(name) {
println("Hello $name!") }
String[] names = ["SintSi", "Kaitlyn", "Keira"]
for (name in names) {
sayHello(name)
}
List
Data manipulation, such as list and map processing, tends to be tedious when working with Java. This is where the
Groovy language shines. Check the difference of declaring a list between Java and Groovy:
List javaList = new ArrayList() // Java
def groovyList = [] // Groovy
Both are instance of java.util.List
Initializing is simple
def alist = [5, 1, 3, 5]
def myList = [10, "John", new Integer(5), new Double(7.6d)]
Appending items is like this:
def alist = [10, 9, 8]
alist << 7
alist << 6
printing the contents will result to output: [10, 9, 8, 7, 6]
List javaList = new ArrayList() // Java
def groovyList = [] // Groovy
Both are instance of java.util.List
Initializing is simple
def alist = [5, 1, 3, 5]
def myList = [10, "John", new Integer(5), new Double(7.6d)]
Appending items is like this:
def alist = [10, 9, 8]
alist << 7
alist << 6
printing the contents will result to output: [10, 9, 8, 7, 6]
You can create a new list by using each item in a list to evaluate an expression:
def alist = [1,2,3,4,5]
println alist.collect{it * 10}
Output will be: [10, 20, 30, 40, 50]
Or you can create a new list by invoking a function on each items:
def alist = ["Apple", "Basketball", "Championship"]
println alist*.length()
This creates a new list by getting the length() of each item.
The output is: [5, 10, 12]
def alist = [1,2,3,4,5]
println alist.collect{it * 10}
Output will be: [10, 20, 30, 40, 50]
Or you can create a new list by invoking a function on each items:
def alist = ["Apple", "Basketball", "Championship"]
println alist*.length()
This creates a new list by getting the length() of each item.
The output is: [5, 10, 12]
Maps
Map stores a list of key value pairs. For example:
def emptyMap = [:]
def mapWithValues = [fruit:'Apple', veggie:'Carrot']
def emptyMap = [:]
def mapWithValues = [fruit:'Apple', veggie:'Carrot']
The only difference between an empty map and list is the extra colon.
It is also an instance of java.util.
Map and all keys are Strings by default.
Here are sample ways to add and get items from maps:
def alist = [fruit:'Apple', 'veggie':'Carrot']
alist['car'] = 'Sedan'
alist.put('book', 'Novels')
alist << [pet:'Dog']
println alist['fruit']
println alist.'veggie'
println alist.get('car')
println alist.get('book')
println alist.get('pet')
def alist = [fruit:'Apple', 'veggie':'Carrot']
alist['car'] = 'Sedan'
alist.put('book', 'Novels')
alist << [pet:'Dog']
println alist['fruit']
println alist.'veggie'
println alist.get('car')
println alist.get('book')
println alist.get('pet')
Notice that fruit, even without quotes was treated as String.
Map operations such as put and get are also supported.
Loops
Here are example of simple but commonly used loops.
To execute something multiple times:
5.times {
println "Hello"
}
This will print Hello 5 times.
Looping through items of a list
['cat', 'dog', 'hamster'].each { name -> println name } Will output: cat dog hamster
Replace for loop with a number range and looping with each item:
6..10).each { number -> println number } Will output the numbers from 6 to 10
[fruit:'Apple', veggie:'Carrot', car:'Sedan'].each { key, value -> println "${key} = ${value}" }
Will outputfruit = Apple veggie = Carrot car = Sedan
________________________________________________________________________________
Setup Windows Development Environment For Groovy and Grails
Overview
• Install JDK
• Install Grails
• Setup Environment Variables
• Configure Groovy / Grails Tool Suite
• Create and run a sample application
Install JDK
• Recommended JDk version: 1.6
• Download the JDK installer file using the following url:
• http://www.oracle.com/technetwork/java/javase/downloads/jdk6u38-downloads-1877406.html
• Just run and follow instructions
Install Grails
• Go to Grails website and download the latest version of Grails (3.3.4)
• http://grails.org
• And just extract it in your C drive:
Setup Environment Variables
• GRAILS_HOME - C:\grails-3.3.4
• JAVA_HOMe - C:\Program Files\Java\jdk1.8.0_121
• PATH – append the executable (bin) directories to the end of previous value for both jdk and grails
• test if everything is ok by going to command line and typing
• javac -version
• grails -version
• Install groovy / grails tool suite
• Download GGTS (Groovy on grails tool suite)
• http://www.springsource.org/downloads/sts-ggts
• Extract to your c drive
• Now run the program
• C:\springsource\ggts-3.3.0.RELEASE\GGTS.exe:
Configure Groovy / Grails Tool Suite
• We have to make sure that the Java run time of our IDE points to a JDK instead of a JRE. Here are the steps:
Go to Window > Preferences > Java > Installed JRE:
Go to Window > Preferences > Java > Installed JRE:
• Edit installed JRE if it is pointing to a JRE installation
• Change it to the JDK installation directory installed in the steps above. It is better if you also change the Name:
• JRE home : C:\Program Files\Java\jdk1.8.0_121
• JRE name : jdk1.8
• Make sure you have an installed Grails SDK:
Windows > Preferences > Groovy > Grails
Windows > Preferences > Groovy > Grails
Choose the grails version in the ggts-bundle
Create and run a sample application
• File > New > Grails Project
• Give it a name – sample
• Use default grails installation
• Use default location
• Click finish
• The project will be created with default skeleton directories and files.
• Open Grails Console:
• Type "run-app" and hit the Enter key
• Check the console and wait for the message "Server running".
• Now you can open the application in your browser to test:
_________________________________________________________________________________
Data types Conditionals And loops
Data Types in groovy
Groovy data types can be
categorized into simple data types and collective data types.
Simple data types include
strings, regular expressions (regexes), and numbers.
Collective data types include lists, maps, and ranges. Groovy offers support for such data
types at the language level, meaning
that it offers native syntax for declaring and using special operators on them.
Groovy control structures can be categorized into conditional structures and looping structures.
Conditional structures include the
If statement, the ternary operator (;?), and the
switch statement.
Looping structures include
the while and for loops.
Groovy Data types
In any programming language, you need to use various
variables to store various types of information. Variables are nothing but
reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory to store the value associated with
the variable.
Built-in data types
Groovy offers a wide variety of built-in data types.
Following is a list of data types which are defined in Groovy −
byte − This is used
to represent a byte value. An example is 2.
short − This is used
to represent a short number. An example is 10.
int − This is used
to represent whole numbers. An example is 1234.
long − This is used
to represent a long number. An example is 10000090.
float − This is used
to represent 32-bit floating point numbers. An example is 12.34.
double − This is used
to represent 64-bit floating point numbers which are longer decimal number
representations which may be required at times. An example is 12.3456565.
char − This defines
a single character literal. An example is ‘a’.
Boolean − This
represents a Boolean value which can either be true or false.
String − These are
text literals which are represented in the form of chain of characters.
For example “Hello World”.
Class Numeric
Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed −
java.lang.Byte
java.lang.Short
java.lang.Integer
java.lang.Long
java.lang.Float
java.lang.Double
In addition, the following classes can be used for
supporting arbitrary precision arithmetic −
java.math.BigInteger
java.math.BigDecimal
Example of built in data types
The following code example showcases how the different
built-in data types can be used −
class Example {
static void main(String[] args) {
//Example of a int datatype
int x = 5;
//Example of a long datatype
long y = 100L;
//Example of a floating point datatype
float a = 10.56f;
//Example of a double datatype
double b = 10.5e40;
//Example of a BigInteger datatype
BigInteger bi = 30g;
//Example of a BigDecimal datatype
BigDecimal bd = 3.5g;
println(x); println(y); println(a); println(b);
println(bi); println(bd);
}
}
Groovy - Variables
Variables in Groovy can be defined in two ways − using
the native syntax for the data type or the next is by using the def
keyword. For variable definitions it is mandatory to either provide a type
name explicitly or to use "def" in replacement. This is required by
the Groovy parser.
There are following basic types of variable in Groovy
as explained in the previous chapter −
byte − This is used
to represent a byte value. An example is 2.
short − This is used
to represent a short number. An example is 10.
int − This is used
to represent whole numbers. An example is 1234.
long − This is used
to represent a long number. An example is 10000090.
float − This is used
to represent 32-bit floating point numbers. An example is 12.34.
double − This is used
to represent 64-bit floating point numbers which are longer decimal number
representations which may be required at times. An example is 12.3456565.
char − This defines
a single character literal. An example is ‘a’.
Boolean − This
represents a Boolean value which can either be true or false.
String − These are
text literals which are represented in the form of chain of characters.
For example “Hello World”.
Groovy also allows for additional types of variables
such as arrays, structures and classes which we will see in the subsequent
chapters.
Variable Declarations
class Example {
static void main(String[] args) {
// x is defined as a variable
String x = "Hello";
// The value of the variable is printed to the console
println(x); } }
Printing Variables
You can print the current value of a variable with the
println function. The following example shows how this can be achieved.
class Example {
static void main(String[] args) {
//Initializing 2 variables
int x = 5; int X = 6;
//Printing the value of the variables to the console
println("The value of x is " + x + "The
value of X is " + X);
}
}
Control structures
Groovy supports the usual if - else syntax from Java
def x = false
def y = false
if ( !x ) {
x = true
}
assert x == true
if ( x ) {
x = false
} else {
y = true
}
assert x == y
Groovy also supports the normal Java
"nested" if then else if syntax:
if ( ... ) {
...
} else if (...) {
...
} else {
...
}
switch / case
One difference though is that the Groovy switch
statement can handle any kind of switch value and different kinds of matching
can be performed.
def x = 1.23
def result = ""
switch ( x ) {
case "foo":
result = "found foo"
// lets fall through
case "bar":
result += "bar"
case [4, 5, 6, 'inList']:
result = "list"
break
case 12..30:
result = "range"
break
case Integer:
result = "integer"
break
case Number:
result = "number" break
default: result = "default"
} assert result == "number"
Loops in groovy
Groovy For Loop with Times
3.times {
println "Hello World ${it}"
}
Output
Hello World 0 Hello World 1 Hello World 2
Groovy For Loop with List
def list = ["A", "B",
"C"]
for (item in list) {
println item
}
def map = [a1:'b1', a2:'b2']
for ( item in map ) {
println item.key
}
def map = [a1:'b1', a2:'b2']
for ( item in map ) {
println item.value
}
Groovy while loop example
class Example {
static void main(String[] args) {
int count = 0;
while(count<5)
{ println(count); count++;
}
}
}
for-in statement
class Example {
static void main(String[] args) {
int[] array = [0,1,2,3];
for(int i in array) { println(i);
}
}
}
___________________________________________________________________________________
Closures , Currying
closure
A closure is a short anonymous block of code. It just
normally spans a few lines of code.
A method can even take the block of code as a
parameter. They are anonymous in nature.
Following is an example of a simple closure and what
it looks like.
class Example {
static void main(String[] args) {
def clos = {println "Hello World"};
clos.call();
}
}
Closures in Groovy
The simpliest explanation of a closure in Groovy is
that it is anonymous function.
def closure = { println "I am a closure" }
//closure is defined
closure() // Prints I am a closure
Ok, so first point here is that I am a
closure is not printed when the closure is defined but only when it is
invoked.
Closures facilitate delayed execution.
It is also possible to pass parameters to a
closure
closure
In the above example, the code line –
{println "Hello World"}
is known as a closure. The code block referenced by
this identifier can be executed with the call statement.
When we run the above program, we will get the
following result −
Hello World
Formal parameters in closures
Closures can also contain formal parameters to make
them more useful just like methods in Groovy.
class Example {
static void main(String[] args) {
def clos = {param->println "Hello
${param}"};
clos.call("World");
}
}
In the above code example, notice the use of the
${param } which causes the closure to take a parameter. When calling the
closure via the clos.call statement we now have the option to pass a parameter
to the closure.
When we run the above program, we will get the
following result −
Closure using implicit parameter
The next illustration repeats the previous example and
produces the same result, but shows that an implicit single parameter referred
to as it can be used. Here ‘it’ is a keyword in Groovy.
class Example {
static void main(String[] args) {
def clos = {println "Hello ${it}"};
clos.call("World");
}
}
When we run the above program, we will get the
following result −
Hello World
Closure having only one parameter
When the closure has only one parameter, we don't even
need the -> we can just use the implicit it variable.
def closureWithParameters = { println it }
closureWithParameter("Hello dude") // Prints Hello dude
Passing parameters to closure
def closureWithParameters = {x, y -> print(x +
" and " + y)}
closureWithParameters("Hello dudes",
"Hello Mega Dude")
// Prints Hello dudes and Hello Mega Dude
Closures and Variables
More formally, closures can refer to variables at the
time the closure is defined.
Following is an example of how this can be
achieved.
class Example {
static void main(String[] args) {
def str1 = "Hello";
def clos = {param -> println "${str1} ${param}"}
clos.call("World");
/** We are now changing the value of the String str1
which is referenced in the
closure */
str1 = "Welcome";
clos.call("World"); } }
When we run the above program, we will get the
following result −
Hello World
Welcome World
Closures and Variables
In the above example, in addition to passing a
parameter to the closure, we are also defining a variable called str1. The
closure also takes on the variable along with the parameter.
When we run the above program, we will get the
following result −
Hello World Welcome World
Using closures in Methods
Closures can also be used as parameters to methods. In
Groovy, a lot of the inbuilt methods for data types such as Lists and collections
have closures as a parameter type.
The following example shows how a closure can be sent
to a method as a parameter.
Using closures in Methods
class Example {
def static Display(clo) {
/** This time the $param parameter gets replaced by
the string "Inner" */
clo.call("Inner");
}
static void main(String[] args) {
def str1 = "Hello";
def clos = { param -> println "${str1}
${param}" }
clos.call("World");
/** We are now changing the value of the String str1 which is referenced in
the closure*/
str1 = "Welcome";
clos.call("World");
// Passing our closure to a method
Example.Display(clos);
} }
Using closures in Methods
In the above example,
We are defining a static method called Display which
takes a closure as an argument.
We are then defining a closure in our main method and
passing it to our Display method as a parameter.
When we run the above program, we will get the
following result −
Hello World Welcome World Welcome Inner
Using Closures with Lists
class Example {
static void main(String[] args) {
def lst = [11, 12, 13, 14];
lst.each {println it}} }
When we run the above program, we will get the
following result −
11 12 13 14
Using Closures with Maps
class Example {
static void main(String[] args) {
def mp = ["TopicName" : "Maps",
"TopicDescription" : "Methods in Maps"] mp.each {println it}
mp.each {println "${it.key} maps to:
${it.value}"} } }
When we run the above program, we will get the
following result −
TopicName = Maps
TopicDescription = Methods in Maps
TopicName maps to: Maps
TopicDescription maps to: Methods in Maps
class Example {
static void main(String[] args)
{ def lst = [1,2,3,4];
lst.each {println it}
println("The list will only display those numbers
which are divisible by 2")
lst.each{num -> if(num % 2 == 0) println num} }
Currying – Haskell Curry Haskell (prog lang)Curry (concept)
Lets say we have a function called log
def log = {level, date, msg ->
println “$level $date $msg”
}
def today = new Date()
log ‘warning’, today, ‘starting…’
log ‘warning’, today, ‘running…’
log ‘warning’, today, ‘stopping…’
Curry
when you run this you can see that it printed all the
message
It is a little bit noisy
In functional programming functions are expected to
take only one parameter
If a function takes two parameters, you got two
different values to pass in, which means the number of permutation, combination
increases
If a function takes only one parameter there is fewer
values to send
Its easy to proove the correctness of a function when
it takes fewer parameters
It is also more easy to write and reusable
Curry
In our program warning, today is repeated.
Would it be nice if we did not have to send them over
and over again
Notice what I am going to do now
Curry
def log = {level, date, msg ->
println “$level $date $msg”
}
def logWarningToday = log.curry(warning,today)
You went to one closure and you created another
closure from it
This closure has already cached the two values
warning, today
Now we don’t have to repeat those parameters and we
have curried those parameters
So currying allows us to cache and store away certain
properties
def log = {level, date, msg ->
println “$level $date $msg”
}
Def logWarningToday = log.curry(warning,today)
logWarningToday ‘starting…’
logWarningToday ‘running…’
logWarningToday ‘stopping…’
Now what can you curry
In the curry itself, you can either give one
parameter, or two parameters, or three, or all of them depending on how many
you have.
If you give all the parameters, you can just call it
you don’t have to pass any extra parameters because you have given all the
parameters
If you give two parameters, you have to pass one
If you give one you got to pass two
Which parameter are you going to pass – In case of curry you always pass the
rightmost trailing parameter.
If I have to pass two – it will be level and date
If I have to pass one – it will be level
rCurry
rCurry – it curries from the right side
rCurry(v1, v2)
In this case it will be
rCurry(msg, date)
It goes from left to right but the rightmost
parameters
_________________________________________________________________________________
Program Structure - Groovy
1. Package names
Package names play exactly the same role as in Java.
They allows us to separate the code base without any conflicts. Groovy classes
must specify their package before the class definition, else the default
package is assumed.
Defining a package is very similar to Java:
// defining a package named com.yoursite package
com.yoursite
To refer to some class Foo in the com.yoursite.com
package you will need to use the fully qualified name com.yoursite.com.Foo, or
else you can use an import statement as we’ll see below.
Imports
In order to refer to any class you need a qualified
reference to its package. Groovy follows Java’s notion of allowing import
statement to resolve class references.
For example,
Groovy provides several builder classes, such as
MarkupBuilder.
MarkupBuilder is inside the package groovy.xml so in
order to use this class, you need to import it as shown:
// importing the class MarkupBuilder
import groovy.xml.MarkupBuilder
// using the imported class to create an object
def xml = new MarkupBuilder()
assert xml != null
The below imports are added by groovy for you:
Default Imports
Default imports are the imports that Groovy language
provides by default. For example look at the following code:
new Date()
The same code in Java needs an import statement to
Date class like this:
import java.util.Date.
Groovy by default imports these classes for you.
Default Imports
The below imports are added by groovy for you:
import java.lang.* import java.util.* import java.io.*
import java.net.* import groovy.lang.* import groovy.util.* import
java.math.BigInteger import java.math.BigDecimal
Simple import
A simple import is an import statement where you fully
define the class name along with the package. For example the import statement
import groovy.xml.MarkupBuilder in the code below is a simple import which
directly refers to a class inside a package.
// importing the class MarkupBuilder import
groovy.xml.MarkupBuilder
// using the imported class to create an object def
xml = new MarkupBuilder()
assert xml != null
Star import
Groovy, like Java, provides a special way to import
all classes from a package using *, the so called star import. MarkupBuilder is
a class which is in package groovy.xml, alongside another class called
StreamingMarkupBuilder. In case you need to use both classes, you can do:
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
def markupBuilder = new MarkupBuilder()
assert markupBuilder != null
assert new StreamingMarkupBuilder() != null
That’s perfectly valid code. But with a * import, we
can achieve the same effect with just one line. The star imports all the
classes under package groovy.xml:
Start import
import groovy.xml.*
def markupBuilder = new MarkupBuilder() assert
markupBuilder != null
assert new StreamingMarkupBuilder() != null
Static import
Groovy’s static import capability allows you to
reference imported classes as if they were static methods in your own class:
import static Boolean.FALSE
assert !FALSE
//use directly, without Boolean prefix!
This is similar to Java’s static import capability but
is a more dynamic than Java in that it allows you to define methods with the
same name as an imported method as long as you have different types:
Static import
import static java.lang.String.format ……………………1
class SomeClass {
String format(Integer i) { ……………………………2
i.toString()
}
static void main(String[] args) {
assert format('String') == 'String' …………………………….3
assert new SomeClass().format(Integer.valueOf(1)) ==
'1'
}
}
static import of method
of method with same name as method statically imported
above, but with a different parameter type
compile error in java, but is valid groovy code
Note:Please refer next slide for java format method
Format method in java
//how to format in java is given below
The java.lang.String.format(String format,
Object... args) method returns a formatted string using the specified
format string and arguments.
double piVal = Math.PI;
System.out.format("%f\n", piVal);
Scripts versus classes
public static void main vs script
Groovy supports both scripts and classes. Take the
following code for example:
Main.groovy
class Main { ……………………………………………………………………….1
static void main(String... args) { ………………………………..2
println 'Groovy world!' ……………………………………………..3
}
}
define a Main class, the name is arbitrary
the public static void main(String[]) method is usable
as the main method of the class
the main body of the method
This is typical code that you would find coming from
Java, where code has to be embedded into a class to be executable.
Groovy makes it easier, the following code is equivalent:
Script class
Groovy makes it easier, the following code is
equivalent:
Main.groovy
println 'Groovy world!'
A script can be considered as a class without needing
to declare it, with some differences.
A script is always compiled into a class. The
Groovy compiler will compile the class for you, with the body of the script
copied into a run method. The previous example is therefore compiled as if it
was the following:
Main.groovy
import org.codehaus.groovy.runtime.InvokerHelper class
Main extends Script {
def run() {
println 'Groovy world!'
}
static void main(String[] args) {
InvokerHelper.runScript(Main, args)
}
}
The Main class extends the groovy.lang.Script class
groovy.lang.Script requires a run method returning a value the script body goes
into the run method the main method is automatically generated and delegates
the execution of the script on the run method
If the script is in a file, then the base name of the
file is used to determine the name of the generated script class. In this
example, if the name of the file is Main.groovy, then the script class is going
to be Main.
Methods
It is possible to define methods into a script, as
illustrated here:
int fib(int n) {
n < 2 ? 1 : fib(n-1) + fib(n-2) }
assert fib(10)==89
You can also mix methods and code. The generated
script class will carry all methods into the script class, and assemble all
script bodies into the run method:
Mixing methods and code
in Groovy script
in Groovy script
println 'Hello' …………………………………………1
int power(int n) { 2**n } …………………………2
println "2^6==${power(6)}“…………………….3
script begins
a method is defined within the script body
and script continues
This code is internally converted into:
How script is converted
into class internally
into class internally
import org.codehaus.groovy.runtime.InvokerHelper
class Main extends Script {
int power(int n) { 2** n} ………………………………..1
def run() {
println 'Hello' …………………………………2
println "2^6==${power(6)}“…………….3
}
static void main(String[] args) {
InvokerHelper.runScript(Main, args)
} }
the power method is copied as is into the generated
script
class first statement is copied into the run method
second statement is copied into the run method
Even if Groovy creates a class from your script, it is
totally transparent for the user. In particular, scripts are compiled to
bytecode, and line numbers are preserved. This implies that if an exception is
thrown in a script, the stack trace will show line numbers corresponding to the
original script, not the generated code that we have shown.
Variables
Variables in a script do not require a type
definition. This means that this script:
int x = 1
int y = 2
assert x+y == 3
will behave the same as:
x = 1
y = 2
assert x+y == 3
However there is a semantic difference between the two:
if the variable is declared as in the first example,
it is a local variable. It will be declared in the run method that the
compiler will generate and will not be visible outside of the script
main body. In particular, such a variable will not be visible in other
methods of the script
if the variable is undeclared, it goes into the script
binding. The binding is visible from the methods, and is especially
important if you use a script to interact with an application and need to share
data between the script and the application..
If you want a variable to become a field of the class
without going into the Binding, you can use the @Field annotation.
________________________________________________________________________________________
THE END
Comments
Post a Comment