Groovy Introduction at Javaforum 2010

34
1 for Developers by Leonard Axelsson (@xlson) Thursday, June 17, 2010

description

Groovy introduction from the Alt.JVM Language ShootOut at Javaforum in June of 2010. http://www.javaforum.se/jf/archive.jsp#m62

Transcript of Groovy Introduction at Javaforum 2010

Page 1: Groovy Introduction at Javaforum 2010

1

for Developers

by  Leonard  Axelsson  (@xlson)

Thursday, June 17, 2010

Page 2: Groovy Introduction at Javaforum 2010

SweGUG

• Groovy user since 2006• Co-Founder of SweGUG

–Swedish Groovy User Group

• Speaker at GTUG, Agical Geeknight, JFokus, SweGUG

• Developer/Consultant at Qbranch Stockholm

2

Leonard Axelsson

Thursday, June 17, 2010

Page 3: Groovy Introduction at Javaforum 2010

SweGUG

Agenda

• Overview and obligatory Hello World• Syntax Overview• Tips and Trix

3

Thursday, June 17, 2010

Page 4: Groovy Introduction at Javaforum 2010

SweGUG

Groovy Overview

• Originated in 2003• Under the Apache License• Grammar derived from Java 1.5

4

Thursday, June 17, 2010

Page 5: Groovy Introduction at Javaforum 2010

SweGUG

Groovy Overview

• Dynamic language–Inspired by Python, Ruby and Smalltalk

• Object Oriented• Easy to learn for Java devs

–Supports Java style code out of the box

• Scriptable• Embeddable

5

Thursday, June 17, 2010

Page 6: Groovy Introduction at Javaforum 2010

SweGUG

Dynamic Language

• No compile-time checking– int i = “Hello” throws exception at runtime

• Ducktyping– def keyword allows you to care about what the object

does, not what it is

• Supports custom DSLs

6

new  DateDSL().last.day.in.december(  2009  )

Thursday, June 17, 2010

Page 7: Groovy Introduction at Javaforum 2010

SweGUG

Gotchas

• == uses equals()–not object identity–is() used for identity comparission

• return keyword is optional• Methods and classes are public by default• All exceptions are unchecked exceptions• There are no primitives

7

Thursday, June 17, 2010

Page 8: Groovy Introduction at Javaforum 2010

SweGUG

The obligatory Hello World

8

Thursday, June 17, 2010

Page 9: Groovy Introduction at Javaforum 2010

SweGUG

How many in here know Groovy?

9

Thursday, June 17, 2010

Page 10: Groovy Introduction at Javaforum 2010

SweGUG

Groovy can be coded the “Java” way. So basically all of you!

10

Thursday, June 17, 2010

Page 11: Groovy Introduction at Javaforum 2010

SweGUG

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); }}

HelloWorld.java

11

Thursday, June 17, 2010

Page 12: Groovy Introduction at Javaforum 2010

SweGUG

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); }}

HelloWorld.groovy

12

Thursday, June 17, 2010

Page 13: Groovy Introduction at Javaforum 2010

SweGUG

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); }}

Removing ...

13

Thursday, June 17, 2010

Page 14: Groovy Introduction at Javaforum 2010

SweGUG

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!") }}

Removing ...

14

Thursday, June 17, 2010

Page 15: Groovy Introduction at Javaforum 2010

SweGUG

class HelloWorld { public static void main(String[] args) { println("Hello World!") }}

Removing ...

15

Thursday, June 17, 2010

Page 16: Groovy Introduction at Javaforum 2010

SweGUG

println("Hello World!")

Removing ...

16

Thursday, June 17, 2010

Page 17: Groovy Introduction at Javaforum 2010

SweGUG

println "Hello World!"

This is it

17

Thursday, June 17, 2010

Page 18: Groovy Introduction at Javaforum 2010

SweGUG

Feature Overview

• Properties–dynamic getters and setters

• Closures–reusable blocks of code

• Meta Object Protocol–rewrite behaviour at runtime

• Many additions to the JDK

18

Thursday, June 17, 2010

Page 19: Groovy Introduction at Javaforum 2010

SweGUG

Default imports

• java.io.*• java.lang.*• java.math.BigDecimal• java.math.BigInteger• java.net.*• java.util.*• groovy.lang.*• groovy.util.*

19

Thursday, June 17, 2010

Page 20: Groovy Introduction at Javaforum 2010

SweGUG

Strings

20

Thursday, June 17, 2010

Page 21: Groovy Introduction at Javaforum 2010

SweGUG

println "Hello World!"

Remember this?

21

Thursday, June 17, 2010

Page 22: Groovy Introduction at Javaforum 2010

• Macros supported in double-quoted strings

SweGUG

Let’s add something ...

22

String whome = "World!"

println "Hello $whome"

Hello World!

Output:

Thursday, June 17, 2010

Page 23: Groovy Introduction at Javaforum 2010

SweGUG

Plain Old Groovy Objects

23

Thursday, June 17, 2010

Page 24: Groovy Introduction at Javaforum 2010

SweGUG

POGO’s

• Properties–getters and setters are created automatically

• Named Parameters–clarifies intent

24

class Person { String name String lastname}

def anders = new Person(name: 'Anders', lastname: 'Andersson')assert anders.getName() == 'Anders'

// Anders gets married and changes his lastnameanders.setLastname("Sundstedt")assert anders.lastname == "Sundstedt"

Thursday, June 17, 2010

Page 25: Groovy Introduction at Javaforum 2010

SweGUG

POGO’s

• Getters and setters can be overridden

25

class Person { def name def lastname String setLastname(String lastname) { this.lastname = lastname.reverse() }}

def anders = new Person(name: 'Anders', lastname: 'Andersson')

// Anders does a strange change of his lastnameanders.lastname = "Sundstedt"assert anders.lastname == "tdetsdnuS"

Thursday, June 17, 2010

Page 26: Groovy Introduction at Javaforum 2010

SweGUG

Built in syntax for lists and maps

26

Thursday, June 17, 2010

Page 27: Groovy Introduction at Javaforum 2010

SweGUG

Lists

27

def names = ['Leonard', 'Anna', 'Anders']assert names instanceof Listassert names.size() == 3assert names[0] == 'Leonard'

List  syntax:

Thursday, June 17, 2010

Page 28: Groovy Introduction at Javaforum 2010

SweGUG

Maps

28

def map = [name: 'Leonard', lastname: 'Axelsson']assert map.name == 'Leonard'assert map['lastname'] == 'Axelsson'

map.each{ key, value -> println "Key: $key, Value: $value"}

Key: name, Value: LeonardKey: lastname, Value: Axelsson

Output:

Thursday, June 17, 2010

Page 29: Groovy Introduction at Javaforum 2010

SweGUG

each, find and findAll

29

class Person { String name String lastname boolean male}

def ages = [new Person(name: 'Bo', lastname: 'Olsson', male: true), new Person(name: 'Gunn', lastname: 'Bertilsson', male: false), new Person(name: 'Britt', lastname: 'Olsson', male: false)]// Print all namesages.each { println "$it.name $it.lastname" }

// Find one maleassert ages.find{ person -> person.male }.name == 'Bo'

// or find all females assert ages.findAll{ Person p -> !p.male }.size() == 2

Thursday, June 17, 2010

Page 30: Groovy Introduction at Javaforum 2010

SweGUG

Power Asserts

• New in Groovy 1.7

30

// Will throw an assertion errordef getNum() { 5 }assert (1 + 100) == num + 77

Assertion failed:

assert (1 + 100) == num + 77          |      |  |   |          101    |  5   82                 false

at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:378) at ...

Output:

Thursday, June 17, 2010

Page 31: Groovy Introduction at Javaforum 2010

SweGUG

Method not found?

• Better feedback in Groovy 1.7

31

// Will throw a MissingMethodException (no beginsWith method)def carType = "BMW M3"if(carType.beginsWith('Volvo')) { println "It's a Volvo!"}

groovy.lang.MissingMethodException: No signature of method: java.lang.String.beginsWith() is applicable for argument types: (java.lang.String) values: [Volvo]Possible solutions: endsWith(java.lang.String), startsWith(java.lang.String) at ...

Output:

Thursday, June 17, 2010

Page 32: Groovy Introduction at Javaforum 2010

SweGUG

@Grab and grape

• Dependency management using Apache Ivy–Uses Maven Central

• grape commandline tool–Adds dependencies to Groovys global classpath

• @Grab annotation–Great for scripting

32

Thursday, June 17, 2010

Page 33: Groovy Introduction at Javaforum 2010

@Grab(group='org.codehaus.gpars', module='gpars', version='0.10')import groovyx.gpars.GParsExecutorsPool

def importProcessingData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ,18, 19, 20]

time('Parallel execution') { GParsExecutorsPool.withPool { importProcessingData.eachParallel { data -> // Insert arbitrary heavy operation here sleep 200 } }}

time('Linear execution') { importProcessingData.each { // Insert arbitrary heavy operation here sleep 200 }}

def time(String desc, task) { def startTime = new Date().time def result = task() def executionTime = new Date().time - startTime println "$desc took: $executionTime ms." result}

SweGUG

@Grab and GPars

33

Parallel execution took: 1449 ms.Linear execution took: 4006 ms.

Output  (executed  on  dual-­‐core  machine):

Thursday, June 17, 2010

Page 34: Groovy Introduction at Javaforum 2010

SweGUG

Links

• Groovy–http://groovy.codehaus.org/

• Groovy Goodness (great tips and trix)–http://mrhaki.blogspot.com/

• SweGUG–http://groups.google.com/group/swegug

34

Thursday, June 17, 2010