4. Groovy Shell
1. Open a terminal window and type “groovysh”.
2. It allows easy access to evaluate Groovy expressions,
and run simple experiments.
5. Dynamic Typing Vs Static Typing
First, dynamically-typed languages perform type checking at
runtime, while statically typed languages perform type
checking at compile time.
This means that scripts written in dynamically-typed
languages (like Groovy) can compile even if they contain
errors that will prevent the script from running properly (if
at all). If a script written in a statically-typed language
(such as Java) contains errors, it will fail to compile until
the errors have been fixed.
6. // Java example
int num;
num = 5;
// Groovy example
num = 5
Groovy is dynamically-typed and determines its variables'
data types based on their values, so this line is not
required.
7. Strings
● Single Quoted
● Triple Single Quoted
● Double Quoted
● Triple Double Quoted
● Slashy
● Dollar Slashy
9. Operator Overloading
Groovy supports operator overloading which makes working with
Numbers, Collections, Maps and various other data structures
easier to use.
def date = new Date()
date++
println date
All operators in Groovy are method calls.
10. The following few of the operators supported in Groovy and
the methods they map to
● 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)
11. Groovy Truth
In Groovy you can use objects in if and while expressions.
A non-null and non-empty string will evaluate to true.
if("John" ) // any non-empty string is true
if(null) // null is false
if("" ) // empty strings are false
Non zero numbers will evaluate to true.
if(1) // any non-zero value is true
if(-1) // any non-zero value is true
if(0) // zero value is false
12. Groovy Truth For Collection
A non-empty collection will evaluate to true.
List family = ["John" , "Jane" ]
if(family) // true since the list is populated.
And Empty Collection will evaluate to false
List family = [ ]
if(family) // false since the map is not populated.
13. Groovy Classes
In Groovy Classes by default things are public unless you
specify otherwise.
Class Person {
String name
Integer age
}
Person person = new Person()
person.name = “Per
person.age =30
14. If you call person.name=”Groovy”
Then behind the scene
person.setName(“Groovy”)
If you want accidental modification in Groovy, you can add a
pair of getters and setters.
16. Working with Files
new File("foo.txt").bytes
new File("foo.txt").readLines()
new File("foo.txt").eachLine { line -> println(line) }
17. Program structure
1. Package Name
2. Imports
a. Default Imports
b. Simple Imports
c. Star Imports
d. Static Imports
e. Static Star Imports
f. Import aliasing
g. Static Import aliasing
3. Something more and will cover later
20. Import aliasing
import java.util.Date
import java.sql.Date as SQLDate
Date utilDate = new Date(1000L)
SQLDate sqlDate = new SQLDate(1000L)
assert utilDate instanceof java.util.Date
assert sqlDate instanceof java.sql.Date
21. Closures
1. A Closure is a block of code given a name.
2. Groovy has support for closures, which work much like
Java 8 lambdas. A closure is an anonymous block of
executable code.
3. Methods can accept closure as parameters.
4. Defining Closures
22. Syntax
1. Defining a closure
a. {[closureParameters->] statements}
2. Closure as an Object (An instance of groovy.lang.Closure)
a. def listener = {e-> println "Clicked on ${e}"}
3. Calling a closure
a. listener()
b. listener.call()
24. Without Parameters
def helloWorld = {
println "Hello World"
}
Helloworld()
With Parameters
def power = { int x, int y ->
return Math.pow(x, y)
}
println power(2, 3)
25. Implicit parameter
When a closure does not explicitly define a parameter list
(using ->), a closure always defines an implicit parameter,
named it. This means that this code:
def greeting = { "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'
is strictly equivalent to this one:
def greeting = { it -> "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'
26. Implicit parameter
If you want to declare a closure which accepts no argument
and must be restricted to calls without arguments, then you
must declare it with an explicit empty argument list:
def magicNumber = { -> 42 }
// this call will fail because the closure doesn't accept any
argument
magicNumber(11)
27. varargs
It is possible for a closure to declare variable arguments
like any other method. Vargs methods are methods that can
accept a variable number of arguments if the last parameter
is of variable length (or an array) like in the next
examples:
def concat1 = { String... args -> args.join('') }
assert concat1('abc','def') == 'abcdef'
29. Type definition of parameters is the same like variables. If
you define a type you can only use this type, but you can
also skip the type of parameters and pass in anything you
want
def say = { what ->
println what
}
say "Hello World"
30. Closures in gstrings
def x = 1
def gs = "x = ${x}"
assert gs == 'x = 1'
The code behaves as you would expect
32. You will see that the assert fails! There are two reasons for
this:
a GString only evaluates lazily the toString representation
of values
the syntax ${x} in a GString does not represent a closure but
an expression to $x, evaluated when the GString is created.
33. If you need a real closure in a GString and for example
enforce lazy evaluation of variables, you need to use the
alternate syntax ${→ x} like in the fixed example:
def x = 1
def gs = "x = ${-> x}"
assert gs == 'x = 1'
x = 2
assert gs == 'x = 2'
34. Passing Closure
The power of being able to assign closures to variable is
that you can also pass them around to methods.
def transform = { str, transformation ->
transformation(str)
}
def myFun = { it.toUpperCase() }
println transform("Hello World", myFun)
35. class EvenNumberCalculations {
static main(args) {
def obj = new EvenNumberCalculations()
obj.printEvenNumbers(10)
def result = obj.calculateSumOfEvenNumbers(10);
println('Total: ' + result)
result = obj.calculateProductOfEvenNumbers(10);
println('Product: ' + result)
result = obj.calculateSquareOfEvenNumbers(10);
println('Squared: ' + result)
}
def printEvenNumbers(int n){
for(int i = 2; i <= n; i += 2) {
println(i)
}
}
int calculateSumOfEvenNumbers(int n){
def sum = 0;
for(int i = 2; i <= n; i += 2) {
sum += i
}
return sum;
}
int calculateProductOfEvenNumbers(int n){
def product = 1;
for(int i = 2; i <= n; i += 2) {
product *= i
}
return product;
}
int[] calculateSquareOfEvenNumbers(int n){
def squared = []
for(int i = 2; i <= n; i += 2) {
squared << i ** 2
}
return squared;
}
}
36. class EvenNumberCalculationsWithClosure {
static main(args) {
def obj = new EvenNumberCalculationsWithClosure()
obj.pickEvenNumbers(10, { println it })
def total = 0
obj.pickEvenNumbers(10) { total += it }
println('Total: ' + total)
def product = 1
obj.pickEvenNumbers(10) { product *= it }
println('Product: ' + product)
def squared = []
obj.pickEvenNumbers(10) { squared << it ** 2 }
println('Squared: ' + squared)
}
def pickEvenNumbers(n, block) {
for(int i = 2; i <= n; i += 2) {
block(i)
}
}
}