Groovy
* Scripting / Agile Dynamic Language for JVM
* Features inspired from Python, Ruby.
* Syntax very close to Java and Same OO model as Java
* Seamless integration with all existing Java classes and libraries.
* Groovy code Compiles to Java bytecode.
* Can run on .Net 2.0 using IKVM
* Latest version 1.6
* http://groovy.codehaus.org
Groovy Basic
1. Closures
2. Dynamic Methods
3. List & Maps
4. Better XML/Swing Capabilities
5. Permits operator Overloading
6. GString: interpolated String
1. Closure :
=> Closures are reusable blocks of code
=> One or more program statements enclosed in curly brackets “{}”
=> Closures do not require a class or a method name
=> Can be passed around like variables
=> The statements within a closure are not executed until the call() is made
=> Return is using an explicit return statement or the value of the last executed statement.
=> E.g. square = { it * it } //“it” implicit parameter representing the passed value.
square (4) // Output = 16
def name = "Gaju"
def printClosure = { println "Hello, ${name}" } //output : Hello, Gaju
//Passing Parameters to Closures
def printClosure = {name -> println "Hello, ${name}" }
printClosure("Gaju") //output : Hello, Gaju
def list = [‘hritbh’, ‘sagar’, ‘somkant’]
def sayHello = {println it}
list.each(sayHello)
Sample class & script:
class Speaker {
String name
def age
String toString() { "MY name is $name and I'm $age“ }
public static void main(String []args){
def speaker = new Speaker(name:'Gajanan Koram', age:27)
println speaker.toString()
def speakers = [new Speaker(name:'Rod Johnson', age:36),
new Speaker(name:'Guillaume Laforge', age:29)]
def upper = { it.toString().toUpperCase() }
speakers.findAll { name -> name =~ /.*od.*/ }.collect(upper).each { println it }
}
}
/*
Compile code : groovyc Speaker.groovy
run : groovy Speaker
output : MY name is Gajanan Koram and I'm 27
MY NAME IS ROD JOHNSON AND I'M 36
*/
2. Dynamic Methods:
=> Add new methods to an object at runtime
=> Intercept non-existent method calls :
• Tracing and debugging
• Mocks and stubs
=> Meta-Object Protocol : changes structure and behaviour at runtime
class webcamp{
def haveTea() {
println"Time for tea"
}
}
camp = new webcamp()
camp.haveTea()
Eg. Add a new method “haveSamosa”
camp = new webcamp()
camp.haveTea()
webcamp.metaClass.haveSamosa= { ->
println"Have Samosaalso"
}
camp = new webcamp()
// Create a fresh object since the class has changed!
camp.haveSamosa()
3. Lists and Maps:
=> Lists look like arrays but are of type java.util.List plus new methods.
[1,2,3] + [1] == [1,2,3,1]
[1,2,3] << 1 ="=">
[1,2,3,1] - [1] == [2,3]
[1,2,3] * 2 == [1,2,3,1,2,3]
[1,[2,3]].flatten() == [1,2,3]
[1,2,3].reverse() == [3,2,1]
[1,2,3].intersect([4,3,1]) == [3,1]
[1,2,3].collect{ it+3 } == [4,5,6]
[1,2,3,1].unique().size() == 3
[1,2,3,1].count(1) == 2
[1,2,3,4].min() == 1
[1,2,3,4].max() == 4
[1,2,3,4].sum() == 10
[4,2,1,3].sort() == [1,2,3,4]
[4,2,1,3].findAll{it%2 == 0} == [4,2]
=> Maps are like lists that have an arbitrary type of key instead of integer.
def map = [a:0, b:1]
Map iteration methods take the nature of Map.Entry objects into account.
map.each { key, value ->
println "$key $value"
}
4. Building XML
def writer = new StringWriter()
def bldr = new groovy.xml.MarkupBuilder(writer )
bldr.languages {
language(name: 'C++' ) { author('Stroustrup' )}
language(name: 'Java' ) { author('Gosling' )}
language(name: 'Lisp' ) { author('McCarthy' )}
}
println writer
Output :
Stroustrup
Gosling
McCarthy
5. Operator Overloading
=> Groovy uses operator overloading to create shortcuts that make Java friendlier.
For example, adding an object to a list in Java looks like this: myList.add(someObject).
The corresponding Groovy way of adding an object to a list is
myList <<>
=> Groovy operators and their corresponding methods.
Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a ** b a.power(b)
a / b a.div(b)
a % b a.mod(b)
a | b a.or(b)
a & b a.and(b)
a ^ b a.xor(b)
a++ or ++a a.next()
a-- or --a a.previous()
a[b] a.getAt(b)
a[b] = c a.putAt(b, c)
a << style=""> a.leftShift(b)
a >> b a.rightShift(b)
switch(a) { case(b) : } b.isCase(a)
~a a.bitwiseNegate()
-a a.negative()
+a a.positive()
Comments