Intruduction to
Groovy & Grails
Groovy, what is it?
Groovy
is a relatively new agile dynamic language
for the Java platform
exists since 2004
belongs to the family of modern easy to use
Groovy‘s magic
Groovy
is
simpler
to write than Java
advanced features allow for
fewer lines of code
Groovy
relies on Java
all Java APIs can be used with
Groovy
use
Groovy
to get rid of semicolons and other
annoying must haves in Java
rewriting Java code to
Groovy
01 package hs-owl.korte.gex; 02 03 import java.util.List; 04 import java.util.ArrayList; 05 0607 public class Task { 08 private String name; 09 private String descr; 10
11 public Task() {} 12
13 public Task(String name,
String descr) { 14 this.name = name;
15 this.descr = descr; 16 }
17
18 public String getName() { 19 return name;
20 } 21
22 public void setName(String name) { 23 this.name = name;
25
26 public String getDescr() { 27 return descr;
28 } 29
30 public void setDescr(String de) { 31 descr = de;
32 } 33
34 public static void main(String[] args) { 35 List tasks = new ArrayList();
36 tasks.add(new Task("1", "first")); 37 tasks.add(new Task("2", "second")); 38 tasks.add(new Task("3","third")); 39 40 for(Task ag : tasks) 41 System.out.println(ag.getName() + " " + ag.getDescr()); 42 } 43 } 44 }
simplifying the code
01 package hs-owl.korte.gex02
03 public class Task { 04
05 private String name 06 private String descr 07
08 public static void main(String[] args) { 09 def tasks = new ArrayList()
10 tasks.add(new Task (name:"1", descr:"first")) 11 tasks.add(new Task (name:"2", descr:"second")) 12 tasks.add(new Task (name:"3", descr:"third")) 13 14 for(Task ag : tasks)
15 println "$(ag.name) $(ag.descr)"
16 } 17 } 18 }
example as Groovy class:
implicitly included packages
no semicolons necessary
simpler println statement
optional typing in line 09
further simplifying the
code
01 package hs-owl.korte.gex 02
03 public class Task { 04
05 private String name 06 private String descr 07
08 public static void main(String[] args) { 09 def tasks = [
10 new Task(name:"1", descr:"first"), 11 new Task(name:"2", descr:"second"), 12 new Task(name:"3", descr:"third") 13 ]
14
15 tasks.each {
16 println "$(it.name) $(it.descr)"
17 } 18 } 19 }
using Groovy's collection
and map notation
for statement replaced
with closure in line 09
closure = reusable block of code
can be passed to methods, defined
using keyword def
ArrayList is expressed as
[ ]
closure is passed to each
method, which is provided for
collections (line 15)
getting rid of the main
method
01 package hs-owl.korte.gex 02
03 public class Task { 04
05 private String name 06 private String descr 07
08 } 09
09 def tasks = [
10 new Task(name:"1", descr:"first"), 11 new Task(name:"2", descr:"second"), 12 new Task(name:"3", descr:"third") 13 ]
14
15 tasks.each {
16 println "$(it.name) $(it.descr)"
17 } 18 } 19 }