Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Groovy

Introduction to Groovy

Anton Arhipov

January 30, 2013
Tweet

More Decks by Anton Arhipov

Other Decks in Programming

Transcript

  1. James  Strachan   29  Aug  2003  Groovy  –  the  birth

     of     new  dynamic  language  for  Java   PlaOorm   July  2009  “I  can  honestly  say  if  someone  had     shown  me  the  Programming  in  Scala  book  back     in  2003  I’d  probably  never  created  Groovy”   h0p://radio-­‐weblogs.com/0112098/2003/08/29.html    
  2. Плюшки   •  Скрипты!   •  Коллекции   •  GPath

      •  “Строители”   •  Метапрограммирование   •  Экосистема  
  3. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! Динамическая   типизация,   GString  
  4. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! String longer = “””Hello, $name, ! Groovy is really cool!”””! Статическая   типизация,   «многострочность»  
  5. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! String longer = “””Hello, $name, ! Groovy is really cool!”””! assert 1.5 == 3/2! BigDecimal   equals()  
  6. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! String longer = “””Hello, $name, ! Groovy is really cool!”””! assert 1.5 == 1/2! def printSize(obj){! print obj?.size()! }! «утиная»   типизация   безопасное   разыменование   ссылок  
  7. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! String longer = “””Hello, $name, ! Groovy is really cool!”””! assert 1.5 == 1/2! def printSize(obj){! print obj?.size()! }! def pets = [‘dog’,’cat’]! pets.each {pet ->! assert pet < ‘dog’! }! Специальный   синтаксис  для   коллекций   замыкания  и   перегрузка   операторов  
  8. System.out.println(“Hello, World!”);! println ‘Hello, World!’! def name = ‘Anton’! println

    “Hello, $name!”! String longer = “””Hello, $name, ! Groovy is really cool!”””! assert 1.5 == 1/2! def printSize(obj){! print obj?.size()! }! def pets = [‘dog’,’cat’]! pets.each {pet ->! assert pet < ‘dog’! }!
  9. import java.util.List;! import java.util.ArrayList;! class Erase {! private List removeLongerThan(List

    strings, int length) {! List result = new ArrayList();! for (String s: strings) {! if (s.length() <= length) {! result.add(s);! }! }! return result;! }! ! public static void main(String[] args) {! List names = new ArrayList();! names.add("Вася"); names.add("Коля");! names.add("Петя"); names.add("Фёдор");! System.out.println(names);! Erase e = new Erase();! List shortNames = e.removeLongerThan(names, 4);! System.out.println(shortNames.size());! for (String s: shortNames) {! System.out.println(s);! }! }! }! Java  ==  Groovy  
  10. import java.util.List;! import java.util.ArrayList;! class Erase {! private List removeLongerThan(List

    strings, int length) {! List result = new ArrayList();! for (String s: strings) {! if (s.length() <= length) {! result.add(s);! }! }! return result;! }! ! public static void main(String[] args) {! List names = new ArrayList();! names.add("Вася"); names.add("Коля");! names.add("Петя"); names.add("Фёдор"); ! System.out.println(names);! Erase e = new Erase();! List shortNames = e.removeLongerThan(names, 4); ! System.out.println(shortNames.size());! for (String s: shortNames) {! System.out.println(s);! }! }! }! Импорты  по-­‐умолчанию   ;  необязателен  
  11. class Erase {! private List removeLongerThan(List strings, int length) {!

    List result = new ArrayList()! for (String s: strings) {! if (s.length() <= length) {! result.add(s)! }! }! return result! }! ! public static void main(String[] args) {! List names = new ArrayList()! names.add("Вася") names.add("Коля") ! names.add("Петя") names.add("Фёдор") ! System.out.println(names)! Erase e = new Erase()! List shortNames = e.removeLongerThan(names, 4) ! System.out.println(shortNames.size())! for (String s: shortNames) {! System.out.println(s)! }! }! }!
  12. class Erase {! private List removeLongerThan(List strings, int length) {!

    List result = new ArrayList()! for (String s: strings) {! if (s.length() <= length) {! result.add(s)! }! }! return result! }! ! public static void main(String[] args) {! List names = new ArrayList()! names.add("Вася") names.add("Коля") ! names.add("Петя") names.add("Фёдор") ! System.out.println(names)! Erase e = new Erase()! List shortNames = e.removeLongerThan(names, 4)! System.out.println(shortNames.size())! for (String s: shortNames) {! System.out.println(s)! }! }! }! Динамическая  типизация   Не  надо  определять  класс  и  main()   length  и  size  
  13. def removeLongerThan(strings, length) {! def result = new ArrayList()! for

    (s in strings) {! if (s.size() <= length) {! result.add(s)! }! }! return result! }! ! names = new ArrayList()! names.add("Вася") ! names.add("Коля") ! names.add("Петя") ! names.add("Фёдор") ! System.out.println(names)! shortNames = e.removeLongerThan(names, 4)! System.out.println(shortNames.size())! for (s: shortNames) {! System.out.println(s)! }!
  14. def removeLongerThan(strings, length) {! def result = new ArrayList()! for

    (s in strings) {! if (s.size() <= length) {! result.add(s)! }! }! return result! }! ! names = new ArrayList()! names.add("Вася") ! names.add("Коля") ! names.add("Петя")! names.add("Фёдор")! System.out.println(names)! shortNames = e.removeLongerThan(names, 4)! System.out.println(shortNames.size())! for (s: shortNames) {! System.out.println(s)! }! Нотация  для  списков   Упрощённая  работа  со  списками   return  необязателен  
  15. def removeLongerThan(strings, length) {! strings.findAll { it.size() <= length }!

    }! ! names = ["Вася", "Коля", "Петя", "Фёдор"]! System.out.println(names)! shortNames = e.removeLongerThan(names, 4)! System.out.println(shortNames.size())! shortNames.each { System.out.println(s) }!
  16. def removeLongerThan(strings, length) {! strings.findAll { it.size() <= length }!

    }! ! names = ["Вася", "Коля", "Петя", "Фёдор"]! System.out.println(names)! shortNames = e.removeLongerThan(names, 4)! System.out.println(shortNames.size())! shortNames.each { System.out.println(s) }! Ненужный  метод!   Убрать  ненавистный  System.out  !   Скобки  в  сад!  
  17. names = ["Вася", "Коля", "Петя", "Фёдор"]! println names! shortNames =

    names.findAll { it.size() <= 4 }! println shortNames.size()! shortNames.each { println it }! [Вася,  Коля,  Петя,  Федя]   3   Вася   Коля   Петя  
  18. def list = [1, 2, 3, 4, 5, 5]! assert

    list.get(2) == 3! assert list[2] == 3! assert list instanceOf java.util.List!
  19. def list = [1, 2, 3, 4, 5, 5]! assert

    list.get(2) == 3! assert list[2] == 3! assert list instanceOf java.util.List! def list = [1, 2, 3, 4, 5, 5] as Set! assert list.size() == 5! assert list instanceOf java.util.Set! !
  20. def range = 5..8! assert range.size() == 4! assert range[2]

    == 7! assert range.contains(5)! ! ! !
  21. def range = 5..8! assert range.size() == 4! assert range[2]

    == 7! assert range.contains(5)! ! def range = 5..<8! assert range.size() == 3! assert ! range.contains(8)! ! ! !
  22. def range = 5..8! assert range.size() == 4! assert range[2]

    == 7! assert range.contains(5)! ! def range = 5..<8! assert range.size() == 3! assert ! range.contains(8)! ! assert range.from == 5! assert range.to == 7! ! !
  23. def range = ‘a’..’d’! assert range.size() == 4! assert range[2]

    == ‘c’! assert range.contains(‘a’)! assert ! range.contains(‘e’)! ! !
  24. for(i in 1..10) { ! println “${i}” ! }! !

    (1..10).each { ! println “$it” ! }! ! switch(years){! case 1..10: rate = 1.015; break; ! case 11..25: rate = 0.905; break;! default: rate = 0.755; ! }!
  25. def map = [name:’Anton’, age:28, id:2]! assert map[’name’] == 'Anton’!

    assert map.id == 2! assert map instanceOf java.util.Map! ! ! !
  26. def map = [name:’Anton’, age:28, id:2]! assert map[’name’] == 'Anton’!

    assert map.id == 2! assert map instanceOf java.util.Map! ! def empty = [:]! empty.foo = 25! assert empty.foo == 25! ! !
  27. ['test', 12, 20, true].grep(Boolean)! ! ['test', 'Groovy', 'Java'].grep(~/^G.*/)! ! ['a',

    'b', 'c', 'd'].grep(['b', 'c'])! ! [1, 15, 16, 30, 12].grep(12..18)! ! [12.300, 109.20, 42.031].grep(42.031)! ! [10, 20, 30, 50, 100].grep({ it > 50 })!
  28. def  text  ="""          <cars>    

             <car  name='HSV  Maloo'  year='2006'>                  <country>Australia</country>              </car>              <car  name='P50'  year='1962'>                  <country>Isle  of  Man</country>              </car>              <car  name='Royale'  year='1931'>                  <country>France</country>              </car>          </cars>   """   def  records  =  new  XmlParser().parseText(text)     cars  =  records.car.grep  {  it.@year  >  '1960'  }   names  =  cars.collect  {it.@name}   [‘HSV  Maloo’,  ‘P50’]  
  29. import groovy.xml.MarkupBuilder! ! def builder = new MarkupBuilder()! ! builder.html

    {! head {! title ”Page Title”! }! body {! p ”My text" ! }! }! <html>      <head>          <•tle>Page  Title</•tle>      </head>      <body>          <p>My  text</p>      </body>   </html>    
  30. import groovy.json.JsonBuilder! ! def builder = new JsonBuilder()! def root

    = builder.me {! name ”Anton”! lastName ”Arhipov”! age 13! }! {"me":{"name":"Anton","lastName":"Arhipov","age":13}}   [me:[name:Anton,  lastName:Arhipov,  age:13]]   println builder! println root!
  31. ant.sequential {! echo("inside sequential")! myDir = "target/AntTest/"! mkdir(dir:myDir)! copy(todir:myDir) {!

    fileset(dir:"src/test") {! include(name:"**/*.groovy")! }! }! echo("done")! }! def ant = new AntBuilder()! import groovy.util.AntBuilder!
  32. class Foo {! ! }! ! foo = new Foo()!

    ! foo.hello()! groovy.lang.MissingMethodExcep^on:  No  signature  of  method:   Foo.hello()  is  applicable  for  argument  types:  ()  values:  []   Possible  solu•ons:  sleep(long),  sleep(long,  groovy.lang.Closure),   each(groovy.lang.Closure),  split(groovy.lang.Closure),   getAt(java.lang.String),  wait()  
  33. def invokeMethod(String name, args){! def call = args[0]! println "<$name>"!

    if(call instanceof Closure){! call.delegate = this! call.call()! } else {! println call.toString()! }! println "</$name>" ! }!