groovy & grails - lecture 2

Alexandre Masselot
Alexandre MasselotConsultant at OCTO Technology Switzerland à OCTO Technology
Groovy: Efficiency Oriented Programming
Lecture 2
Master Proteomics & Bioinformatics - University of Geneva
Alexandre Masselot - summer 2010
Contents

• Eclipse IDE basics
• Assertions
• Closures
• I/O
• Functions
• Control structures
Eclipse IDE

• Eclipse is mainly known as a versatile Integrated Development
  Environment (http://eclipse.org) although it can be much more
Eclipse IDE

• Eclipse is mainly known as a versatile Integrated Development
  Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
Eclipse IDE

• Eclipse is mainly known as a versatile Integrated Development
  Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
• We will use the prepackaged Springsource Tool Suite (http://
  www.springsource.com/products/sts)
  • start STS
     • help > dashboard,
     • tab extensions

     • install groovy and grails
     • restart eclipse
Eclipse IDE

• Eclipse is mainly known as a versatile Integrated Development
  Environment (http://eclipse.org) although it can be much more
• Eclipse IDE itself is a naked framework, enriched by plugins
• We will use the prepackaged Springsource Tool Suite (http://
  www.springsource.com/products/sts)
  • start STS
     • help > dashboard,
     • tab extensions

     • install groovy and grails
     • restart eclipse
• Plenty of other plugins can be installed Help > Install new software
Eclipse IDE : a super simple setup

• starting eclipse => run into a workspace, i.e. a disk directory
Eclipse IDE : a super simple setup

• starting eclipse => run into a workspace, i.e. a disk directory

• one workspace hosts projects (sub directory strcture)
Eclipse IDE : a super simple setup

• starting eclipse => run into a workspace, i.e. a disk directory

• one workspace hosts projects (sub directory strcture)
• create a project New > Project > Groovy
Eclipse IDE : a super simple setup

• starting eclipse => run into a workspace, i.e. a disk directory

• one workspace hosts projects (sub directory strcture)
• create a project New > Project > Groovy
• You can change the workspace when working for totally different aspect of
  a project (e.g. one for practicals, one for a more lab internship)
Eclipse IDE : a super simple setup

• a project contains several directories
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
   • bin/ where the compiler write machine ready files
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
   • bin/ where the compiler write machine ready files

   • test/ where the test files (will) resides
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
   • bin/ where the compiler write machine ready files

   • test/ where the test files (will) resides
   • lib/ etc.
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
   • bin/ where the compiler write machine ready files

   • test/ where the test files (will) resides
   • lib/ etc.
• In the src directory, you can create packages. Package names are
  delimiteid with dot e.g. mpb.practicals.lec1
Eclipse IDE : a super simple setup

• a project contains several directories
   • src/ for the source file (the code you type)
   • bin/ where the compiler write machine ready files

   • test/ where the test files (will) resides
   • lib/ etc.
• In the src directory, you can create packages. Package names are
  delimiteid with dot e.g. mpb.practicals.lec1

• In practice, you will find a directory src/mpb/praticals/lec1/
Eclipse IDE : a super simple setup
Eclipse IDE : a super simple setup


• Then, you can create a new script : New > File > MyScript.groovy
Eclipse IDE : a super simple setup


• Then, you can create a new script : New > File > MyScript.groovy
• Run the script with Right button > Run as > groovy script
7
How do you know that your code works?




                                        8
Assertions
Assertions


To check a code validity, one solution is to call print statements
 List l=[1, 2, 7, 4]
 def x=l.max()
 println “max is $x”
Assertions


To check a code validity, one solution is to call print statements
 List l=[1, 2, 7, 4]
 def x=l.max()
 println “max is $x”

Relies on human reading...
Assertions
Assertions


Use assertions that will clearly report failure if any, and be silent if none
 assert x == 7
Assertions


Use assertions that will clearly report failure if any, and be silent if none
 assert x == 7
Any boolean value can be tested
 assert [1, 7, 4] == l-2
 assert “my funny valentine” == my_song
Assertions


Use assertions that will clearly report failure if any, and be silent if none
 assert x == 7
Any boolean value can be tested
 assert [1, 7, 4] == l-2
 assert “my funny valentine” == my_song

assert statement are heavily used in test driven programming
assert   report only on error




                                11
write code




             12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
write code   check it works




                              12
Closures



“Let’s start with a simple definition of closures[...]. A closure is a piece of code
wrapped up as an object[...]. It’s a normal object in that you can pass a
reference to it around just as you can a reference to any other object”

                        (Groovy in Action - 5.1 A gentle introduction to closures)
Closures



“Let’s start with a simple definition of closures[...]. A closure is a piece of code
wrapped up as an object[...]. It’s a normal object in that you can pass a
reference to it around just as you can a reference to any other object”

                        (Groovy in Action - 5.1 A gentle introduction to closures)

Closure is a master feature of the groovy language. Although it can be used
in complex situations, closure are also part of daily programming.
Closures


It can be seen as a method attached to an object
 List l=[1, 1, 2, 3, 5, 8, 13]
 l.each{println it}            //it is the default iterator
Closures


It can be seen as a method attached to an object
 List l=[1, 1, 2, 3, 5, 8, 13]
 l.each{println it}            //it is the default iterator
The iterator can also be named
 l.each{myVal -> println “value $myVal”}
 “my funny valentine”.each{println $it} // -> m
                                         //   y ...
Closures                                         (cont’d)

Much more closures are available on list
 l.eachWithIndex{val, i -> println “list[$i]=$val”}
Closures                                           (cont’d)

Much more closures are available on list
 l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
 l.findAll{ it%2 == 0}              // -> [2, 8]
Closures                                                 (cont’d)

Much more closures are available on list
 l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
 l.findAll{ it%2 == 0}              // -> [2, 8]
Make global boolean test
 l.every{ it < 20 }                 // -> true (all values are <20)
 l.any{ it < 0 }                    // -> false (none is negative)
Closures                                                 (cont’d)

Much more closures are available on list
 l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
 l.findAll{ it%2 == 0}              // -> [2, 8]
Make global boolean test
 l.every{ it < 20 }                 // -> true (all values are <20)
 l.any{ it < 0 }                    // -> false (none is negative)
Transform
 l.collect{ it*10}                  // [10, 10, 20 , 30, 50, ...]
Closures                                                 (cont’d)

Much more closures are available on list
 l.eachWithIndex{val, i -> println “list[$i]=$val”}
Find even values
 l.findAll{ it%2 == 0}              // -> [2, 8]
Make global boolean test
 l.every{ it < 20 }                 // -> true (all values are <20)
 l.any{ it < 0 }                    // -> false (none is negative)
Transform
 l.collect{ it*10}                  // [10, 10, 20 , 30, 50, ...]
Or even piped
 l.findAll{ it%2 == 0}.collect{ it*10 } // -> [20, 80]
Closures (on map)

Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
                          ‘simone’:new Date(‘4/2/1985’),
                          ‘birgit’:new Date(’12/6/1988’)]
Closures (on map)

 Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
                           ‘simone’:new Date(‘4/2/1985’),
                           ‘birgit’:new Date(’12/6/1988’)]
A simple loop
 birthdays.each{
      println “${it.key} born in “ + it.value.year
 }
Closures (on map)

 Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
                           ‘simone’:new Date(‘4/2/1985’),
                           ‘birgit’:new Date(’12/6/1988’)]
A simple loop
 birthdays.each{
      println “${it.key} born in “ + it.value.year
 }
Or with name parameters
 birthday.each{name, date -> println “$name : $date”}
Closures (on map)

 Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’),
                           ‘simone’:new Date(‘4/2/1985’),
                           ‘birgit’:new Date(’12/6/1988’)]
A simple loop
 birthdays.each{
      println “${it.key} born in “ + it.value.year
 }
Or with name parameters
 birthday.each{name, date -> println “$name : $date”}
Sort on the month order
 birthdays.sort{it.value.month}
          .each{println “${it.key} born in “ + it.value}
I/O : reading standard input

Without any connection to outside, a script is soon meaningless...
I/O : reading standard input

Without any connection to outside, a script is soon meaningless...
Reading can be done from stdin (standard input)
 System.in.eachLine{ ... }           // loop on all line piped in
I/O : reading standard input

Without any connection to outside, a script is soon meaningless...
Reading can be done from stdin (standard input)
 System.in.eachLine{ ... }           // loop on all line piped in

Or interactively
 Scanner stdin=new Scanner(System.in)
 int i=stdin.nextInt()
 stdin.<CTRL-space>
I/O: reading from Files

File myFile=new File(“path/to/my/file”)
I/O: reading from Files

 File myFile=new File(“path/to/my/file”)
Loop through the lines
 myFile.eachLine{...}

 myFile.splitEachLine(/s+/){
    // it is an array with all
    // the elements of the current line
 }
I/O: reading from Files

 File myFile=new File(“path/to/my/file”)
Loop through the lines
 myFile.eachLine{...}

 myFile.splitEachLine(/s+/){
    // it is an array with all
    // the elements of the current line
 }
Or get the total text at once
 myFile.getText()
I/O: reading from Files

 File myFile=new File(“path/to/my/file”)
Loop through the lines
 myFile.eachLine{...}

 myFile.splitEachLine(/s+/){
    // it is an array with all
    // the elements of the current line
 }
Or get the total text at once
 myFile.getText()
Temporary file are often necessary
 File myTmpFile=File.createTempFile(‘prefix’, ‘.suf’)
 myTmpFile.deleteOnExit()
Functions

Function is a piece of code that takes argument and returns a value (like a
sub in perl)
Functions

Function is a piece of code that takes argument and returns a value (like a
sub in perl)

Parameters can be statically or dynamically typed
 int increment(x, i){
   return x+i
 }
 int j=3
 println increment(j, 5)               // -> 8
Functions
Functions


Depending on argument type, the method is guessed
 def increment(int x)   {return x + 1 }
 def increment(double x){return x + 0.1}

 println increment(3)                   // -> 4
 println increment(3.0)                 // -> 3.1
Functions


Depending on argument type, the method is guessed
 def increment(int x)   {return x + 1 }
 def increment(double x){return x + 0.1}

 println increment(3)                   // -> 4
 println increment(3.0)                 // -> 3.1
Functions
Functions



def increment(List l)   {l << 1 }
def increment(String s){return s + 1}

println increment([3, 4])       // -> [3, 4, 1]
println increment(“abcd”)       // -> “abcd1”
Functions                                               (cont’d)

Number of arguments induces the function called
 int increment (x, i){ return x+i }
 int increment (x)   { return x+1 }

 println increment(3)                         // -> 4
 println increment(3, 4)                      // -> 7
More concisely, parameters can be defined by default
 int increment(x, i=1){              // if no second arg => i=1
   return x+i
 }

 println increment(3, 5)                      // -> 8
 println increment(3)                         // -> 4
Functions                                               (cont’d)

Number of arguments induces the function called
 int increment (x, i){ return x+i }
 int increment (x)   { return x+1 }

 println increment(3)                         // -> 4
 println increment(3, 4)                      // -> 7
More concisely, parameters can be defined by default
 int increment(x, i=1){              // if no second arg => i=1
   return x+i
 }

 println increment(3, 5)                      // -> 8
 println increment(3)                         // -> 4
Functions                                               (cont’d)

Number of arguments induces the function called
 int increment (x, i){ return x+i }
 int increment (x)   { return x+1 }

 println increment(3)                         // -> 4
 println increment(3, 4)                      // -> 7
More concisely, parameters can be defined by default
 int increment(x, i=1){              // if no second arg => i=1
   return x+i
 }

 println increment(3, 5)                      // -> 8
 println increment(3)                         // -> 4
Functions                                               (cont’d)

Number of arguments induces the function called
 int increment (x, i){ return x+i }
 int increment (x)   { return x+1 }

 println increment(3)                         // -> 4
 println increment(3, 4)                      // -> 7
More concisely, parameters can be defined by default
 int increment(x, i=1){              // if no second arg => i=1
   return x+i
 }

 println increment(3, 5)                      // -> 8
 println increment(3)                         // -> 4
Functions                                           (cont’d)

We can always use a Map with for named parameters

 int increment(params){
      return (params.x?:0)     + // ?:0 0 if params.x false
             (params.plus?:0) -
             (params.minus?:0)
 }
 increment(x:3, plus:4)         // -> 7
Functions                                                    (cont’d)

We can always use a Map with for named parameters

 int increment(params){
      return (params.x?:0)     + // ?:0 0 if params.x false
             (params.plus?:0) -
             (params.minus?:0)
 }
 increment(x:3, plus:4)         // -> 7
Method described fully with map arguments will be extensively used when
calling action from url
1 sur 73

Contenu connexe

Tendances(20)

Unfiltered UnveiledUnfiltered Unveiled
Unfiltered Unveiled
Wilfred Springer3.3K vues
groovy & grails - lecture 6groovy & grails - lecture 6
groovy & grails - lecture 6
Alexandre Masselot458 vues
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
Wim Godden1.1K vues
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden16.4K vues
Little Big RubyLittle Big Ruby
Little Big Ruby
LittleBIGRuby654 vues
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
Nikita Popov15K vues
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
Thomas Weinert8.2K vues
Ggug spockGgug spock
Ggug spock
Skills Matter1.3K vues
Cli the other SAPI confoo11Cli the other SAPI confoo11
Cli the other SAPI confoo11
Combell NV1.6K vues
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar2.8K vues
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
osfameron799 vues
Perl 6 by examplePerl 6 by example
Perl 6 by example
Andrew Shitov1.7K vues

Similaire à groovy & grails - lecture 2

RubyRuby
RubyKerry Buckley
1.2K vues75 diapositives
Groovy presentationGroovy presentation
Groovy presentationManav Prasad
2.4K vues69 diapositives
PHP PPT FILEPHP PPT FILE
PHP PPT FILEAbhishekSharma2958
41 vues32 diapositives
Php introductionPhp introduction
Php introductionOsama Ghandour Geris
103 vues28 diapositives

Similaire à groovy & grails - lecture 2(20)

RubyRuby
Ruby
Kerry Buckley1.2K vues
Groovy presentationGroovy presentation
Groovy presentation
Manav Prasad2.4K vues
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma295841 vues
Php introductionPhp introduction
Php introduction
Osama Ghandour Geris103 vues
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
Sanjeev Kumar Jaiswal1K vues
Lets make better scriptsLets make better scripts
Lets make better scripts
Michael Boelen125 vues
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov15.6K vues
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu8.9K vues
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell24.3K vues
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
lachie354 vues
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
Dave Cross7.2K vues
Shell ScriptShell Script
Shell Script
Adam Victor Brandizzi208 vues
Groovy unleashed Groovy unleashed
Groovy unleashed
Isuru Samaraweera404 vues
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
Isuru Samaraweera201 vues
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
Workhorse Computing1.4K vues
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
Garth Gilmour177 vues
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
Workhorse Computing511 vues
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
osfameron1.6K vues

Plus de Alexandre Masselot(9)

groovy & grails - lecture 8groovy & grails - lecture 8
groovy & grails - lecture 8
Alexandre Masselot689 vues
groovy & grails - lecture 10groovy & grails - lecture 10
groovy & grails - lecture 10
Alexandre Masselot629 vues
groovy & grails - lecture 1groovy & grails - lecture 1
groovy & grails - lecture 1
Alexandre Masselot889 vues
groovy & grails - lecture 13groovy & grails - lecture 13
groovy & grails - lecture 13
Alexandre Masselot1.1K vues
groovy & grails - lecture 9groovy & grails - lecture 9
groovy & grails - lecture 9
Alexandre Masselot1.6K vues
groovy & grails - lecture 7groovy & grails - lecture 7
groovy & grails - lecture 7
Alexandre Masselot574 vues

Dernier(20)

ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web Developers
Maximiliano Firtman161 vues
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)
CSUC - Consorci de Serveis Universitaris de Catalunya59 vues
Green Leaf Consulting: Capabilities DeckGreen Leaf Consulting: Capabilities Deck
Green Leaf Consulting: Capabilities Deck
GreenLeafConsulting177 vues
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf
Eleanor McHugh36 vues

groovy & grails - lecture 2

  • 1. Groovy: Efficiency Oriented Programming Lecture 2 Master Proteomics & Bioinformatics - University of Geneva Alexandre Masselot - summer 2010
  • 2. Contents • Eclipse IDE basics • Assertions • Closures • I/O • Functions • Control structures
  • 3. Eclipse IDE • Eclipse is mainly known as a versatile Integrated Development Environment (http://eclipse.org) although it can be much more
  • 4. Eclipse IDE • Eclipse is mainly known as a versatile Integrated Development Environment (http://eclipse.org) although it can be much more • Eclipse IDE itself is a naked framework, enriched by plugins
  • 5. Eclipse IDE • Eclipse is mainly known as a versatile Integrated Development Environment (http://eclipse.org) although it can be much more • Eclipse IDE itself is a naked framework, enriched by plugins • We will use the prepackaged Springsource Tool Suite (http:// www.springsource.com/products/sts) • start STS • help > dashboard, • tab extensions • install groovy and grails • restart eclipse
  • 6. Eclipse IDE • Eclipse is mainly known as a versatile Integrated Development Environment (http://eclipse.org) although it can be much more • Eclipse IDE itself is a naked framework, enriched by plugins • We will use the prepackaged Springsource Tool Suite (http:// www.springsource.com/products/sts) • start STS • help > dashboard, • tab extensions • install groovy and grails • restart eclipse • Plenty of other plugins can be installed Help > Install new software
  • 7. Eclipse IDE : a super simple setup • starting eclipse => run into a workspace, i.e. a disk directory
  • 8. Eclipse IDE : a super simple setup • starting eclipse => run into a workspace, i.e. a disk directory • one workspace hosts projects (sub directory strcture)
  • 9. Eclipse IDE : a super simple setup • starting eclipse => run into a workspace, i.e. a disk directory • one workspace hosts projects (sub directory strcture) • create a project New > Project > Groovy
  • 10. Eclipse IDE : a super simple setup • starting eclipse => run into a workspace, i.e. a disk directory • one workspace hosts projects (sub directory strcture) • create a project New > Project > Groovy • You can change the workspace when working for totally different aspect of a project (e.g. one for practicals, one for a more lab internship)
  • 11. Eclipse IDE : a super simple setup • a project contains several directories
  • 12. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type)
  • 13. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type) • bin/ where the compiler write machine ready files
  • 14. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type) • bin/ where the compiler write machine ready files • test/ where the test files (will) resides
  • 15. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type) • bin/ where the compiler write machine ready files • test/ where the test files (will) resides • lib/ etc.
  • 16. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type) • bin/ where the compiler write machine ready files • test/ where the test files (will) resides • lib/ etc. • In the src directory, you can create packages. Package names are delimiteid with dot e.g. mpb.practicals.lec1
  • 17. Eclipse IDE : a super simple setup • a project contains several directories • src/ for the source file (the code you type) • bin/ where the compiler write machine ready files • test/ where the test files (will) resides • lib/ etc. • In the src directory, you can create packages. Package names are delimiteid with dot e.g. mpb.practicals.lec1 • In practice, you will find a directory src/mpb/praticals/lec1/
  • 18. Eclipse IDE : a super simple setup
  • 19. Eclipse IDE : a super simple setup • Then, you can create a new script : New > File > MyScript.groovy
  • 20. Eclipse IDE : a super simple setup • Then, you can create a new script : New > File > MyScript.groovy • Run the script with Right button > Run as > groovy script
  • 21. 7
  • 22. How do you know that your code works? 8
  • 24. Assertions To check a code validity, one solution is to call print statements List l=[1, 2, 7, 4] def x=l.max() println “max is $x”
  • 25. Assertions To check a code validity, one solution is to call print statements List l=[1, 2, 7, 4] def x=l.max() println “max is $x” Relies on human reading...
  • 27. Assertions Use assertions that will clearly report failure if any, and be silent if none assert x == 7
  • 28. Assertions Use assertions that will clearly report failure if any, and be silent if none assert x == 7 Any boolean value can be tested assert [1, 7, 4] == l-2 assert “my funny valentine” == my_song
  • 29. Assertions Use assertions that will clearly report failure if any, and be silent if none assert x == 7 Any boolean value can be tested assert [1, 7, 4] == l-2 assert “my funny valentine” == my_song assert statement are heavily used in test driven programming
  • 30. assert report only on error 11
  • 32. write code check it works 12
  • 33. write code check it works 12
  • 34. write code check it works 12
  • 35. write code check it works 12
  • 36. write code check it works 12
  • 37. write code check it works 12
  • 38. write code check it works 12
  • 39. write code check it works 12
  • 40. write code check it works 12
  • 41. Closures “Let’s start with a simple definition of closures[...]. A closure is a piece of code wrapped up as an object[...]. It’s a normal object in that you can pass a reference to it around just as you can a reference to any other object” (Groovy in Action - 5.1 A gentle introduction to closures)
  • 42. Closures “Let’s start with a simple definition of closures[...]. A closure is a piece of code wrapped up as an object[...]. It’s a normal object in that you can pass a reference to it around just as you can a reference to any other object” (Groovy in Action - 5.1 A gentle introduction to closures) Closure is a master feature of the groovy language. Although it can be used in complex situations, closure are also part of daily programming.
  • 43. Closures It can be seen as a method attached to an object List l=[1, 1, 2, 3, 5, 8, 13] l.each{println it} //it is the default iterator
  • 44. Closures It can be seen as a method attached to an object List l=[1, 1, 2, 3, 5, 8, 13] l.each{println it} //it is the default iterator The iterator can also be named l.each{myVal -> println “value $myVal”} “my funny valentine”.each{println $it} // -> m // y ...
  • 45. Closures (cont’d) Much more closures are available on list l.eachWithIndex{val, i -> println “list[$i]=$val”}
  • 46. Closures (cont’d) Much more closures are available on list l.eachWithIndex{val, i -> println “list[$i]=$val”} Find even values l.findAll{ it%2 == 0} // -> [2, 8]
  • 47. Closures (cont’d) Much more closures are available on list l.eachWithIndex{val, i -> println “list[$i]=$val”} Find even values l.findAll{ it%2 == 0} // -> [2, 8] Make global boolean test l.every{ it < 20 } // -> true (all values are <20) l.any{ it < 0 } // -> false (none is negative)
  • 48. Closures (cont’d) Much more closures are available on list l.eachWithIndex{val, i -> println “list[$i]=$val”} Find even values l.findAll{ it%2 == 0} // -> [2, 8] Make global boolean test l.every{ it < 20 } // -> true (all values are <20) l.any{ it < 0 } // -> false (none is negative) Transform l.collect{ it*10} // [10, 10, 20 , 30, 50, ...]
  • 49. Closures (cont’d) Much more closures are available on list l.eachWithIndex{val, i -> println “list[$i]=$val”} Find even values l.findAll{ it%2 == 0} // -> [2, 8] Make global boolean test l.every{ it < 20 } // -> true (all values are <20) l.any{ it < 0 } // -> false (none is negative) Transform l.collect{ it*10} // [10, 10, 20 , 30, 50, ...] Or even piped l.findAll{ it%2 == 0}.collect{ it*10 } // -> [20, 80]
  • 50. Closures (on map) Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’), ‘simone’:new Date(‘4/2/1985’), ‘birgit’:new Date(’12/6/1988’)]
  • 51. Closures (on map) Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’), ‘simone’:new Date(‘4/2/1985’), ‘birgit’:new Date(’12/6/1988’)] A simple loop birthdays.each{ println “${it.key} born in “ + it.value.year }
  • 52. Closures (on map) Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’), ‘simone’:new Date(‘4/2/1985’), ‘birgit’:new Date(’12/6/1988’)] A simple loop birthdays.each{ println “${it.key} born in “ + it.value.year } Or with name parameters birthday.each{name, date -> println “$name : $date”}
  • 53. Closures (on map) Map<String, Date> birthdays=[‘paul’:new Date(‘5/4/1983’), ‘simone’:new Date(‘4/2/1985’), ‘birgit’:new Date(’12/6/1988’)] A simple loop birthdays.each{ println “${it.key} born in “ + it.value.year } Or with name parameters birthday.each{name, date -> println “$name : $date”} Sort on the month order birthdays.sort{it.value.month} .each{println “${it.key} born in “ + it.value}
  • 54. I/O : reading standard input Without any connection to outside, a script is soon meaningless...
  • 55. I/O : reading standard input Without any connection to outside, a script is soon meaningless... Reading can be done from stdin (standard input) System.in.eachLine{ ... } // loop on all line piped in
  • 56. I/O : reading standard input Without any connection to outside, a script is soon meaningless... Reading can be done from stdin (standard input) System.in.eachLine{ ... } // loop on all line piped in Or interactively Scanner stdin=new Scanner(System.in) int i=stdin.nextInt() stdin.<CTRL-space>
  • 57. I/O: reading from Files File myFile=new File(“path/to/my/file”)
  • 58. I/O: reading from Files File myFile=new File(“path/to/my/file”) Loop through the lines myFile.eachLine{...} myFile.splitEachLine(/s+/){ // it is an array with all // the elements of the current line }
  • 59. I/O: reading from Files File myFile=new File(“path/to/my/file”) Loop through the lines myFile.eachLine{...} myFile.splitEachLine(/s+/){ // it is an array with all // the elements of the current line } Or get the total text at once myFile.getText()
  • 60. I/O: reading from Files File myFile=new File(“path/to/my/file”) Loop through the lines myFile.eachLine{...} myFile.splitEachLine(/s+/){ // it is an array with all // the elements of the current line } Or get the total text at once myFile.getText() Temporary file are often necessary File myTmpFile=File.createTempFile(‘prefix’, ‘.suf’) myTmpFile.deleteOnExit()
  • 61. Functions Function is a piece of code that takes argument and returns a value (like a sub in perl)
  • 62. Functions Function is a piece of code that takes argument and returns a value (like a sub in perl) Parameters can be statically or dynamically typed int increment(x, i){ return x+i } int j=3 println increment(j, 5) // -> 8
  • 64. Functions Depending on argument type, the method is guessed def increment(int x) {return x + 1 } def increment(double x){return x + 0.1} println increment(3) // -> 4 println increment(3.0) // -> 3.1
  • 65. Functions Depending on argument type, the method is guessed def increment(int x) {return x + 1 } def increment(double x){return x + 0.1} println increment(3) // -> 4 println increment(3.0) // -> 3.1
  • 67. Functions def increment(List l) {l << 1 } def increment(String s){return s + 1} println increment([3, 4]) // -> [3, 4, 1] println increment(“abcd”) // -> “abcd1”
  • 68. Functions (cont’d) Number of arguments induces the function called int increment (x, i){ return x+i } int increment (x) { return x+1 } println increment(3) // -> 4 println increment(3, 4) // -> 7 More concisely, parameters can be defined by default int increment(x, i=1){ // if no second arg => i=1 return x+i } println increment(3, 5) // -> 8 println increment(3) // -> 4
  • 69. Functions (cont’d) Number of arguments induces the function called int increment (x, i){ return x+i } int increment (x) { return x+1 } println increment(3) // -> 4 println increment(3, 4) // -> 7 More concisely, parameters can be defined by default int increment(x, i=1){ // if no second arg => i=1 return x+i } println increment(3, 5) // -> 8 println increment(3) // -> 4
  • 70. Functions (cont’d) Number of arguments induces the function called int increment (x, i){ return x+i } int increment (x) { return x+1 } println increment(3) // -> 4 println increment(3, 4) // -> 7 More concisely, parameters can be defined by default int increment(x, i=1){ // if no second arg => i=1 return x+i } println increment(3, 5) // -> 8 println increment(3) // -> 4
  • 71. Functions (cont’d) Number of arguments induces the function called int increment (x, i){ return x+i } int increment (x) { return x+1 } println increment(3) // -> 4 println increment(3, 4) // -> 7 More concisely, parameters can be defined by default int increment(x, i=1){ // if no second arg => i=1 return x+i } println increment(3, 5) // -> 8 println increment(3) // -> 4
  • 72. Functions (cont’d) We can always use a Map with for named parameters int increment(params){ return (params.x?:0) + // ?:0 0 if params.x false (params.plus?:0) - (params.minus?:0) } increment(x:3, plus:4) // -> 7
  • 73. Functions (cont’d) We can always use a Map with for named parameters int increment(params){ return (params.x?:0) + // ?:0 0 if params.x false (params.plus?:0) - (params.minus?:0) } increment(x:3, plus:4) // -> 7 Method described fully with map arguments will be extensively used when calling action from url

Notes de l'éditeur

  1. \n
  2. IDE basics\nhorizontal layers for learning\nmotto of the semester : keep the code concise!!\nwe&amp;#x2019;ll focus on features of less than 10 lines. (-&gt;7)\n\n
  3. Try plugins (tasks etc...)\nbut exp =&gt; do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&amp;#x2019;ll see the most useful shortcuts bit by bit\n\n
  4. Try plugins (tasks etc...)\nbut exp =&gt; do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&amp;#x2019;ll see the most useful shortcuts bit by bit\n\n
  5. Try plugins (tasks etc...)\nbut exp =&gt; do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&amp;#x2019;ll see the most useful shortcuts bit by bit\n\n
  6. Try plugins (tasks etc...)\nbut exp =&gt; do not mix too much . install eclipse in different directories\nuse shortcuts!!!\ncustomize them. Little mouse. we&amp;#x2019;ll see the most useful shortcuts bit by bit\n\n
  7. (+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&amp;#x2019;t forget to close project to limit noise\n
  8. (+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&amp;#x2019;t forget to close project to limit noise\n
  9. (+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&amp;#x2019;t forget to close project to limit noise\n
  10. (+ some meta-information) \nsetup will greatly be enhanced when we will build more than just scripts\nCTRL-Shift-F11 (or something close, depending on your setup) to relaunch the script\nCtrl-space demo\ndon&amp;#x2019;t forget to close project to limit noise\n
  11. do not touch build/ explicitely\n
  12. do not touch build/ explicitely\n
  13. do not touch build/ explicitely\n
  14. do not touch build/ explicitely\n
  15. do not touch build/ explicitely\n
  16. do not touch build/ explicitely\n
  17. do not touch build/ explicitely\n
  18. we will come back often to discover more possibilities in using eclipse...\ndon&amp;#x2019;t forget to close project to limit noise\n
  19. we will come back often to discover more possibilities in using eclipse...\ndon&amp;#x2019;t forget to close project to limit noise\n
  20. we will come back often to discover more possibilities in using eclipse...\ndon&amp;#x2019;t forget to close project to limit noise\n
  21. \n
  22. \n
  23. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  24. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  25. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  26. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  27. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  28. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  29. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  30. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  31. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  32. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  33. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  34. \n
  35. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  36. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  37. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  38. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  39. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  40. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  41. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  42. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  43. test driven is programming in 2 steps:\n * define the goal through assertions\n * fulfill the tests writing the code\n
  44. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  45. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  46. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  47. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  48. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  49. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  50. Even the simplest def is a bit beyond understanding...\nit is like $_ in perl\nnote the curly brackets\n
  51. go google!!!\nWe will be always able to see a 1% of the possibilities\n
  52. go google!!!\nWe will be always able to see a 1% of the possibilities\n
  53. go google!!!\nWe will be always able to see a 1% of the possibilities\n
  54. go google!!!\nWe will be always able to see a 1% of the possibilities\n
  55. go google!!!\nWe will be always able to see a 1% of the possibilities\n
  56. see the new Date(string)\nbirthday.each -&gt; loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
  57. see the new Date(string)\nbirthday.each -&gt; loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
  58. see the new Date(string)\nbirthday.each -&gt; loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
  59. see the new Date(string)\nbirthday.each -&gt; loop on Map Entry (key/value)\nin fact, a linkedMap (order is kept)\nhow to sort with decreasing month (dec, nov,...january)\n
  60. often have automated reading through file \nparameters are passed as command arguments or into a file\n
  61. often have automated reading through file \nparameters are passed as command arguments or into a file\n
  62. often have automated reading through file \nparameters are passed as command arguments or into a file\n
  63. don&amp;#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
  64. don&amp;#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
  65. don&amp;#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
  66. don&amp;#x2019;t forget that most of the commons manipulations are already programmed in the core library\nFile delete, exist, find all file names etc.. \n
  67. avoid \n
  68. avoid \n
  69. avoid \n
  70. avoid \n
  71. avoid \n
  72. avoid \n
  73. avoid \n
  74. better write \nint increment(x){ return increment(x, 1)}\n
  75. better write \nint increment(x){ return increment(x, 1)}\n
  76. better write \nint increment(x){ return increment(x, 1)}\n
  77. better write \nint increment(x){ return increment(x, 1)}\n
  78. we&amp;#x2019;ll see ?: later\n
  79. we&amp;#x2019;ll see ?: later\n