Your SlideShare is downloading. ×
Introduction to Groovy
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to Groovy

559

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
559
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. [грýви]  
  • 2. Привет!  @antonarhipov   @jrebel   Java,  Groovy  
  • 3. Немного  истории   Rhino  1995   1997   2001   2003   2011   BeanShell
  • 4. James  Strachan   29  Aug  2003  Groovy  –  the  birth  of     new  dynamic  language  for  Java   PlaOorm   h0p://radio-­‐weblogs.com/0112098/2003/08/29.html    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”  
  • 5. Плюшки   •  Скрипты!   •  Коллекции   •  GPath   •  “Строители”   •  Метапрограммирование   •  Экосистема  
  • 6. System.out.println(“Hello, World!”);!println ‘Hello, World!’!
  • 7. System.out.println(“Hello, World!”);!println ‘Hello, World!’! Необязательны:  “;”,   System.out,  (),     метод  main(),     определение  класса  
  • 8. System.out.println(“Hello, World!”);!println ‘Hello, World!’!def name = ‘Anton’!println “Hello, $name!”! Динамическая   типизация,   GString  
  • 9. System.out.println(“Hello, World!”);!println ‘Hello, World!’!def name = ‘Anton’!println “Hello, $name!”!String longer = “””Hello, $name, ! Groovy is really cool!”””! Статическая   типизация,   «многострочность»  
  • 10. 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()  
  • 11. 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()! безопасное  }! разыменование   ссылок  
  • 12. 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’! операторов  }!
  • 13. 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’!}!
  • 14. import java.util.List;!import java.util.ArrayList;!class Erase {! private List removeLongerThan(List strings, int length) {! List result = new ArrayList();! Java  ==  Groovy   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);! }! }!}!
  • 15. 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);! }! }!}!
  • 16. 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)! }! }!}!
  • 17. 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! Не  надо  определять  класс  и  main()  ! }! length  и  size   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)! }! }!}!
  • 18. 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)!}!
  • 19. def removeLongerThan(strings, length) {! def result = new ArrayList()! for (s in strings) {! if (s.size() <= length) {! result.add(s)! }! }! Нотация  для  списков   return result!}! Упрощённая  работа  со  списками   !names = new ArrayList()! return  необязателен  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)!}!
  • 20. 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) }!
  • 21. 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  !   Скобки  в  сад!  
  • 22. names = ["Вася", "Коля", "Петя", "Фёдор"]!println names!shortNames = names.findAll { it.size() <= 4 }!println shortNames.size()!shortNames.each { println it }! [Вася,  Коля,  Петя,  Федя]   3   Вася   Коля   Петя  
  • 23. Коллекции  
  • 24. def list = [1, 2, 3, 4, 5, 5]!assert list.get(2) == 3!assert list[2] == 3!assert list instanceOf java.util.List!
  • 25. 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!!
  • 26. def range = 5..8!assert range.size() == 4!assert range[2] == 7!assert range.contains(5)!!!!
  • 27. 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)!!!!
  • 28. 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!!!
  • 29. def range = ‘a’..’d’!assert range.size() == 4!assert range[2] == ‘c’!assert range.contains(‘a’)!assert ! range.contains(‘e’)!!!
  • 30. 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; !}!
  • 31. def map = [name:’Anton’, age:28, id:2]!assert map[’name’] == Anton’!assert map.id == 2!assert map instanceOf java.util.Map!!!!
  • 32. 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!!!
  • 33. [1,2,3,4,5]*.plus(1)![2,  3,  4,  5,  6]  
  • 34. [1,2,3,4,5]*.plus(1)![2,  3,  4,  5,  6]  [1,2,3,4,5].findAll {it > 3}![4,  5,  6]  
  • 35. [5,2,1,3,4].sort()![1,  2,  3,  4,  5]  
  • 36. [5,2,1,3,4].sort()![1,  2,  3,  4,  5]  [‘ccc’,‘a’,‘bb’].sort {it.size()}![‘a’,  ‘bb’,  ‘ccc’]  
  • 37. [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 })!
  • 38. 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>   [‘HSV  Maloo’,  ‘P50’]  """  def  records  =  new  XmlParser().parseText(text)    cars  =  records.car.grep  {  it.@year  >  1960  }  names  =  cars.collect  {it.@name}  
  • 39. import groovy.xml.MarkupBuilder!!def builder = new MarkupBuilder()!!builder.html {! head {! title ”Page Title”! }! <html>   body {!    <head>   p ”My text" !        <•tle>Page  Title</•tle>   }!    </head>  }!    <body>          <p>My  text</p>      </body>   </html>    
  • 40. import groovy.json.JsonBuilder!!def builder = new JsonBuilder()!def root = builder.me {! name ”Anton”! lastName ”Arhipov”! age 13!}!println builder!{"me":{"name":"Anton","lastName":"Arhipov","age":13}}  println root![me:[name:Anton,  lastName:Arhipov,  age:13]]  
  • 41. import groovy.util.AntBuilder!def ant = new AntBuilder()!ant.sequential {! echo("inside sequential")! myDir = "target/AntTest/"! mkdir(dir:myDir)! copy(todir:myDir) {! fileset(dir:"src/test") {! include(name:"**/*.groovy")! }! }! echo("done")!}!
  • 42. html {! head {! title "Hello"! }! body {! p "Hello"! }!}!
  • 43. html({! head({! title("Hello")! }),! body({! p("Hello")! })!})!
  • 44. html { }!
  • 45. Название  метода   html { }! Параметр   instanceof  Closure  
  • 46. html { }!
  • 47. html { title {} }!
  • 48. html { title { итд } }!
  • 49. invokeMethod! !methodMissing!
  • 50. 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()  
  • 51. class Foo {! def methodMissing(String name, args) {…}!}!!foo = new Foo()!!foo.hello()!
  • 52. 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>" !}!
  • 53. Integer.metaClass {! getEur = { -> delegate + "EUR" }!}!!10.eur!price:  10EUR  
  • 54. import groovy.time.TimeCategory!!use(TimeCategory){! 1.day.from.now!}!
  • 55. groovy.codehaus.org  

×