• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Introduction to Groovy
 

Introduction to Groovy

on

  • 706 views

 

Statistics

Views

Total Views
706
Views on SlideShare
706
Embed Views
0

Actions

Likes
2
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Introduction to Groovy Introduction to Groovy Presentation Transcript

    • [грýви]  
    • Привет!  @antonarhipov   @jrebel   Java,  Groovy  
    • Немного  истории   Rhino  1995   1997   2001   2003   2011   BeanShell
    • 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”  
    • Плюшки   •  Скрипты!   •  Коллекции   •  GPath   •  “Строители”   •  Метапрограммирование   •  Экосистема  
    • System.out.println(“Hello, World!”);!println ‘Hello, World!’!
    • System.out.println(“Hello, World!”);!println ‘Hello, World!’! Необязательны:  “;”,   System.out,  (),     метод  main(),     определение  класса  
    • System.out.println(“Hello, World!”);!println ‘Hello, World!’!def name = ‘Anton’!println “Hello, $name!”! Динамическая   типизация,   GString  
    • System.out.println(“Hello, World!”);!println ‘Hello, World!’!def name = ‘Anton’!println “Hello, $name!”!String longer = “””Hello, $name, ! Groovy is really cool!”””! Статическая   типизация,   «многострочность»  
    • 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()  
    • 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()! безопасное  }! разыменование   ссылок  
    • 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’! операторов  }!
    • 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’!}!
    • 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);! }! }!}!
    • 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);! }! }!}!
    • 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)! }! }!}!
    • 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)! }! }!}!
    • 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)!}!
    • 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)!}!
    • 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) }!
    • 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  !   Скобки  в  сад!  
    • names = ["Вася", "Коля", "Петя", "Фёдор"]!println names!shortNames = names.findAll { it.size() <= 4 }!println shortNames.size()!shortNames.each { println it }! [Вася,  Коля,  Петя,  Федя]   3   Вася   Коля   Петя  
    • Коллекции  
    • 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]!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!!
    • def range = 5..8!assert range.size() == 4!assert range[2] == 7!assert range.contains(5)!!!!
    • 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)!!!!
    • 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!!!
    • def range = ‘a’..’d’!assert range.size() == 4!assert range[2] == ‘c’!assert range.contains(‘a’)!assert ! range.contains(‘e’)!!!
    • 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; !}!
    • def map = [name:’Anton’, age:28, id:2]!assert map[’name’] == Anton’!assert map.id == 2!assert map instanceOf java.util.Map!!!!
    • 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!!!
    • [1,2,3,4,5]*.plus(1)![2,  3,  4,  5,  6]  
    • [1,2,3,4,5]*.plus(1)![2,  3,  4,  5,  6]  [1,2,3,4,5].findAll {it > 3}![4,  5,  6]  
    • [5,2,1,3,4].sort()![1,  2,  3,  4,  5]  
    • [5,2,1,3,4].sort()![1,  2,  3,  4,  5]  [‘ccc’,‘a’,‘bb’].sort {it.size()}![‘a’,  ‘bb’,  ‘ccc’]  
    • [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 })!
    • 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}  
    • 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>    
    • 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]]  
    • 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")!}!
    • html {! head {! title "Hello"! }! body {! p "Hello"! }!}!
    • html({! head({! title("Hello")! }),! body({! p("Hello")! })!})!
    • html { }!
    • Название  метода   html { }! Параметр   instanceof  Closure  
    • html { }!
    • html { title {} }!
    • html { title { итд } }!
    • invokeMethod! !methodMissing!
    • 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()  
    • class Foo {! def methodMissing(String name, args) {…}!}!!foo = new Foo()!!foo.hello()!
    • 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>" !}!
    • Integer.metaClass {! getEur = { -> delegate + "EUR" }!}!!10.eur!price:  10EUR  
    • import groovy.time.TimeCategory!!use(TimeCategory){! 1.day.from.now!}!
    • groovy.codehaus.org