Pobieranie prezentacji. Proszę czekać

Pobieranie prezentacji. Proszę czekać

Groovy Dlaczego Groovy jest groovy? Lech Milewski Mail: Skype: lech.milewski.tt.

Podobne prezentacje


Prezentacja na temat: "Groovy Dlaczego Groovy jest groovy? Lech Milewski Mail: Skype: lech.milewski.tt."— Zapis prezentacji:

1 Groovy Dlaczego Groovy jest groovy? Lech Milewski Mail: L.Milewski@tt.com.plL.Milewski@tt.com.pl Skype: lech.milewski.tt

2 Wstęp Struktura prezentacji Historia Groovy-iego Jak rozpocząć pracę z Groovym Przekształcenie kodu Java na Groovy Dlaczego Groovy jest groovy? Typy Ciągi znaków Wyrażenia regularne Obiekty Operatory Domknięcia Agenda

3 Prezentacja Power Point Kodowanie na żywo Struktura prezentacji

4 Groovy-iego stworzył w 2003 roku James Strachan Open Source (Apache License v2) Dynamiczny język kompilowany do bajktodu języka Java i wykonywany przez JVM. Język rozszerzający Javę z bardzo dużą inspiracją z Pythona, Ruby-iego i Smaltalka Wyjątkowo płaska krzywa uczenia dla programistów Javy Groovy to Java na sterydach! Historia Groovy-iego

5 Instalacja Kompilacja i uruchamianie Skrypty Groovy Powłoka Groovy i konsola. Jak rozpocząć pracę z Groovym

6 Zainstalowane JDK >= 6.0 Paczka zip z Groovym Instalacja - wymagania

7 Należy pobrać archiwum z plikami binarnymi Groovy-iego ze strony Pobierz GroovyPobierz Groovy Wypakować archiwum zip do folderu C:\gr8conf\groovy\ (Windows) lub ~/gr8conf/groovy (Mac/Linux). Ustawić zmienną środowiskową GROOVY_HOME na identyczny katalog jak w poprzednim kroku. Dodaj katalog [GROOVY_HOME]\bin do ścieżki systemowej. Windows: Poprzez właściwości komputera dodaj do zmiennej środkowiskowej PATH wartość %GROOVY_HOME%\bin Linux/Mac OS X: otwórz powłokę i ustaw zmienną PATH > export PATH=$PATH:$GROOVY_HOME/bin Instalacja

8 Spójrzmy w końcu w konsolę i jakiś kod! Kompilacja i uruchamianie

9 public class UsingJava { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Using Java " + getName(); } public static void main(String[] args) { UsingJava usingJava = new UsingJava(); usingJava.setName("Geeks"); System.out.println(usingJava); } Przekształcenie kodu Java na Groovy - cz. 1

10 Java Groovy Przekształcenie kodu Java na Groovy - cz. 2 public class UsingJava { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Using Java " + getName(); } public static void main(String[] args) { UsingJava usingJava = new UsingJava(); usingJava.setName("Geeks"); System.out.println(usingJava); } class UsingJava { def name String toString() { "Using Java $name" } static void main(String[] args) { def usingJava = new UsingJava(name: ‘Geeks’) println usingJava }

11 Typy podstawowe Podobne jak w Javie, lecz (nie)opakowane przez odpowiedniki obiektów BigDecimal Typy dynamiczne Typy

12 int intValue = 42 double doubleValue = 1.2080 boolean booleanValue = true char charValue = 'G' assert intValue.class.name == "java.lang.Integer" assert doubleValue.class.name == "java.lang.Double" assert booleanValue.class.name == "java.lang.Boolean" assert charValue.class.name == "java.lang.Character" assert 42.0.class.name == "java.math.BigDecimal" assert 2.100000F + 0.10000F != 3.0 assert 2.1 + 0.1 == 3.0 assert 10G.class.name == "java.math.BigInteger" assert 10L.class.name == "java.lang.Long" assert 10I.class.name == "java.lang.Integer" assert 9.1D.class.name == "java.lang.Double" assert 9.1F.class.name == "java.lang.Float" assert 9.1G.class.name == "java.math.BigDecimal" // Simple method with int type parameter. void methodInt(int value) { assert value == 42 assert value.class.name == "java.lang.Integer" } // Invoke method with int parameter. methodInt intValue Typy podstawowe

13 Integer intValue = 42 def dynamicValue = 42 assert intValue.class.name == "java.lang.Integer" // Static type. assert dynamicValue.class.name == "java.lang.Integer" // Dynamic, strong type. try { intValue = true // Class cast exception. assert false } catch (Exception e) { assert e != null } dynamicValue = true // We can reassign a dynamic type. assert dynamicValue.class.name == "java.lang.Boolean" try { dynamicValue.length() // Invalid method for Boolean type. assert false } catch (Exception e) { assert e != null } Typy dynamiczne

14 Podstawowe GString Wielolinijkowe Ciągi znaków

15 Podstawowe ciągi znaków String singleQuotes = 'Groovy allows single quotes to create a string' String doubleQuotes = "Groovy also allows double quotes, just like in Java" String slashes = /And a third way to create a string/ String dollarSlashes = $/And the fourth way with other escaping rules/$ assert singleQuotes.class.name == "java.lang.String" assert doubleQuotes.class.name == /java.lang.String/ assert slashes.class.name == 'java.lang.String' Ciągi znaków - podstawowe

16 String company = 'Gr8Conf' def message = "${company} - Groovy workshop" assert 'Gr8Conf - Groovy workshop' == message assert message.class.name == "org.codehaus.groovy.runtime.GStringImpl" def convert = /Welcome to '${company.toLowerCase()}'/ assert "Welcome to 'gr8conf'" == convert assert convert.class.name == "org.codehaus.groovy.runtime.GStringImpl" Ciągi znaków - GString

17 def tableName = 'Groovy' def sql = """ select count(*) from ${tableName} where id > 100 """ runQuery sql void runQuery(String sql) { assert sql == ''' select count(*) from Groovy where id > 100 ''' } Ciągi znaków – wielowierszowe

18 Pattern Operator (~) Find Operator (=~) Match Operator (==~) Wyrażenia regularne

19 def singleQuotes = ~'[ab]test\\d' assert singleQuotes.class.name == 'java.util.regex.Pattern' def doubleQuotes = ~"string\$" assert doubleQuotes.class.name == 'java.util.regex.Pattern' // Groovy's string slashy syntax is very useful to // define patterns, because we don't have to escape // all those backslashes. def slashy = ~/slashy \d+ value/ assert slashy.class.name == 'java.util.regex.Pattern' def s = 'more' def curlyGString = ~"$s GString" assert curlyGString instanceof java.util.regex.Pattern // Using Pattern.matcher() to create new java.util.regex.Matcher. def last = "t" def testPattern = ~/t..${last}/ assert testPattern.matcher("test").matches() Wyrażenia regularne - Pattern Operator (~)

20 def finder = ('groovy' =~ /gr.*/) assert finder instanceof java.util.regex.Matcher def cool = /gr\w{4}/ // Start with gr followed by 4 characters. def findCool = ('groovy, java and grails rock!' =~ /$cool/) assert 2 == findCool.getCount() assert 'groovy' == findCool[0] // Array-like access to match results. assert 'grails' == findCool[1] // With grouping we get a multidimensional array. def group = ('groovy and grails, ruby and rails' =~ /(\w+) and (\w+)/) assert group.hasGroup() assert 2 == group.getCount() assert 'groovy and grails'== group[0][0] assert 'groovy' == group[0][1] assert 'grails' == group[0][2] assert 'rails' == group[1][2] assert 'ruby' == group[1][1] // Use matcher methods. assert ('Hello world' =~ /Hello/).replaceFirst('Hi') == 'Hi world' Wyrażenia regularne - Find Operator (=~)

21 def matcher = ('groovy' ==~ /gr.*/) assert matcher instanceof Boolean assert !('Groovy rocks!' ==~ /Groovy/) assert 'Groovy rocks!' ==~ /Groovy.*/ Wyrażenia regularne - Match Operator (==~)

22 GroovyBeans Metody/ Multimetody  Domyślne wartości argumentów GPath Wyjątki Obiekty

23 Java Groovy Obiekty – GroovyBeans – cz. 1 package org.gr8conf.java; public class JavaSample { private String userName; private int age; public JavaSample() { } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return userName; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } package org.gr8conf.groovy class GroovySample { String userName int age }

24 import org.gr8conf.java.JavaSample import org.gr8conf.groovy.GroovySample def javaBean = new JavaSample() javaBean.setUserName 'user 1' javaBean.setAge 20 assert javaBean.getUserName() == 'user 1' assert javaBean.getAge() == 20 def groovyBean = new GroovySample() groovyBean.setUserName 'user 2' groovyBean.setAge 19 assert groovyBean.getUserName() == 'user 2' assert groovyBean.getAge() == 19 // We can use a constructor with the names of the properties and their values. javaBean = new JavaSample(userName: 'user 3', age: 25) assert javaBean.getUserName() == 'user 3' assert javaBean.getAge() == 25 // We can use simple assignments instead of setter methods. javaBean.userName = 'user 3a' javaBean.age = javaBean.age + 10 // And we don't have to use the getter method to get the value. assert javaBean.userName == 'user 3a' assert javaBean.age == 35 groovyBean = new GroovySample(userName: 'user 4', age: 30) assert groovyBean.userName == 'user 4' assert groovyBean.age == 30 Obiekty – GroovyBeans – cz. 2

25 String defaultArgs(String message, String append = 'world') { message + ' ' + append } assert 'Hello world' == defaultArgs('Hello') assert 'Hello user' == defaultArgs('Hello', 'user') String optionalArgs(String message, String[] optional) { String result = message for (int i = 0; i < optional.length; i++) { result += ' ' + optional[i] } result } assert 'Hello world' == optionalArgs('Hello', 'world') assert 'Hello world and user' == optionalArgs('Hello', 'world', 'and', 'user') String namedArgs(Map arguments, String message) { "$message $arguments.user, you are $arguments.age years old." } assert 'Hello user, you are 28 years old.' == namedArgs(user: 'user', 'Hello', age: 28) Obiekty - metody

26 // We start off by some very simple class definitions // with a one-level hierarchy amongst them. abstract class Person { String name } class Parent extends Person {} class Child extends Person {} // Now we define methods to return the name with some extra info. def printName(Person person) { "printName(Person): $person.name" } def printName(Child child) { "printName(Child): $child.name" } def printName(p /* dynamic argument */) { "printName(p): $p.name" } // Create new Parent and Child objects but use Person type reference. Person parent1 = new Parent(name: 'parent1') Person child1 = new Child(name: 'child1') assert 'printName(Person): parent1' == printName(parent1) assert 'printName(Child): child1' == printName(child1) // This is not what Java would do!! assert 'printName(Person): child1' == printName(child1 as Person) // Same as what Java would do with printName(child1) // Create objects with type reference is equal to object. Parent parent2 = new Parent(name: 'parent2') Child child2 = new Child(name: 'child2') assert 'printName(Person): parent2' == printName(parent2) assert 'printName(Child): child2' == printName(child2) // Use class outside Person hierarchy. class Dog { String name } assert 'printName(p): buck' == printName(new Dog(name: 'buck')) Obiekty - multimetody

27 class Order { Date date List orderItems } class OrderLine { String product BigDecimal price Integer count def getTotal() { count * price } def orderLines = [ new OrderLine(product: 'PRD1', price: 1.02, count: 10), new OrderLine(product: 'PRD2', price: 8.21, count: 3), new OrderLine(price: 10) ] def order = new Order(orderItems: orderLines) // Use GPath to travers object graph. assert order.orderItems[0].product == 'PRD1' assert order.orderItems[1].price == 8.21 assert order.orderItems[1].total == 3 * 8.21 // Null-safe dereference operator. assert order?.orderItems[1]?.product?.toLowerCase() == 'prd2' assert order.orderItems[2].product?.toLowerCase() == null assert order.orderItems[3]?.product == null GPath

28 try { def url = new URL('malformedUrl') assert false, 'We should never get here because of the exception.' } catch (MalformedURLException e) { assert true assert e in MalformedURLException } // Method throws MalformedURLException, but we don't // have to define it. Groovy will pass the exception // on to the calling code. def createUrl() { new URL('malformedUrl') } try { def url1 = createUrl() assert false, 'We should never get here because of the exception.' } catch (all) { // Groovy shortcut: we can omit the Exception class // if we want to catch all Exception and descendant objects. // In Java we have to write catch (Exception all). assert true assert all in MalformedURLException } Wyjątki

29 Przeciążanie operatorów Operator Spaceship Operator Spread-Dot Operator Spread Operatory

30 Przeciążanie operatorów – cz. 1 OperatorMethod a + ba.plus(b) a - ba.minus(b) a * ba.multiply(b) a ** ba.power(b) a / ba.div(b) a % ba.mod(b) a | ba.or(b) a & ba.and(b) a ^ ba.xor(b) a++ or ++aa.next() a-- or --aa.previous() a[b]a.getAt(b) a[b] = ca.putAt(b, c) a << ba.leftShift(b) a >> ba.rightShift(b) a >>> ba.rightShiftUnsigned(b) switch(a) { case(b) : }b.isCase(a)

31 OperatorMethod ~aa.negate() -aa.negative() +aa.positive() a == ba.equals(b) a != b! a.equals(b) a ba.compareTo(b) a > ba.compareTo(b) > 0 a >= ba.compareTo(b) >= 0 a < ba.compareTo(b) < 0 a <= ba.compareTo(b) <= 0 as as typea.asType(typeClass) Przeciążanie operatorów – cz. 2

32 class Person implements Comparable { String username String email int compareTo(other) { this.username other.username } assert -1 == ('a' 'b') assert 0 == (42 42) assert -1 == (new Person([username:'student', email: 'test@email.com']) new Person([username:'zavaria', email:'tester@email.com'])) assert [1, 2, 3, 4] == [4, 2, 1, 3].sort{ a, b -> a b } Operator Spaceship

33 class Language { String lang def speak() { "$lang speaks." } // Create a list with 3 objects. Each object has a lang // property and a speak() method. def list = [ new Language(lang: 'Groovy'), new Language(lang: 'Java'), new Language(lang: 'Scala') ] // Use the spread-dot operator to invoke the speak() method. assert ['Groovy speaks.', 'Java speaks.', 'Scala speaks.'] == list*.speak() assert ['Groovy speaks.', 'Java speaks.', 'Scala speaks.'] == list.collect{ it.speak() } // We can also use the spread-dot operator to access // properties, but we don't need to, because Groovy allows // direct property access on list members. assert ['Groovy', 'Java', 'Scala'] == list*.lang assert ['Groovy', 'Java', 'Scala'] == list.lang Operator Spread-Dot

34 class Simple { String speak(Integer n, String text, Date date) { def out = new StringBuffer() n.times { out << "Say $text on ${date.format('yyyy-MM-dd')}.\n" } out } } // Spread params list for speak() method. def params = [ 2, "hello world", new Date().parse("yyyy/MM/dd", "2009/09/01") ] assert '''Say hello world on 2009-09-01. Say hello world on 2009-09-01. ''' == new Simple().speak(*params) Operator Spread

35 Integer myInt = 42 Integer anotherInt = myInt Integer newInt = 42 Integer different = 101 assert myInt == anotherInt // In Java: myInt != null && myInt.equals(anotherInt) assert myInt.is(anotherInt) // In Java: myInt == anotherInt assert myInt == newInt assert myInt != different Is vs. ==

36 def defaultItArg = { it - 1 } def result = defaultItArg('Groovy string 1.') // Invoke closure. assert result == 'Groovy string.' assert defaultItArg(44) == 43 assert defaultItArg.call('1') == '' Closure namedArg = { value -> value * 2 } result = namedArg('Groovy') assert result == 'GroovyGroovy' assert namedArg(2) == 4 assert namedArg.call(3) == 6 def multiArgs = { a, b -> a + b } assert multiArgs('Groovy ', 'Java') == 'Groovy Java' assert multiArgs(10, 1) == 11 def noArgs = { -> 'Closure without arguments.' } assert noArgs() == 'Closure without arguments.' assert noArgs.call() == 'Closure without arguments.' Domknięcia

37 Java Groovy Zamienieanie metod w domknięcia package org.gr8conf.java; public class JavaMethods { public static String sayHello(String text) { return "Java says hello to " + text; } package org.gr8conf.groovy String sayHello(text) { "Groovy says hello to $text" } Closure sayHelloClosure = { "Closure says hello to $it" }

38 // Method with two arguments. Last argument is a closure. def work(input, Closure code) { code(input) // Invoke closure! } // Define a closure. def assertJava = { it == 'Java' } work('Java', assertJava) work 'Java', assertJava // No parenthesis. work('Groovy', { assert it == 'Groovy' }) // Anonymous closure as argument. work('Groovy') { assert it == 'Groovy' } // Last argument is closure and can be outside parenthesis. work('Groovy') { assert it == 'Groovy' } // Opening bracket on new line. If we want a code block (e.g. static initializer) instead of closure we must use ; to separate code. work 'Groovy', { assert it == 'Groovy' } // Pay attention, no parenthesis, so comma is needed again! // Does not work: // // Comma between argument list needed: // work 'Groovy' { // assert it == 'Groovy' // } Domknięcia jako parametry metod

39 // Two simple closures with one and two parameters. def one = { it.toUpperCase() } def two = { String s, upper -> if (upper) { s.toUpperCase() } else { s.toLowerCase() } def runClosure(cl) { switch (cl.maximumNumberOfParameters) { case 1: assert [java.lang.Object] == cl.parameterTypes cl.call('Groovy') break case 2: assert [java.lang.String, java.lang.Object] == cl.parameterTypes cl('Groovy', false) break } assert 'GROOVY' == runClosure(one) assert 'groovy' == runClosure(two) O parametrach domknięcia

40 def addNumbers = { x, y, z -> x + y - z } def addOne = addNumbers.curry(1) assert addOne(10, 2) == 9 def subtractOne = addNumbers.rcurry(1) assert subtractOne(10, 2) == 11 def addOneSubtractTwo = addNumbers.ncurry(1, 1, 2) // From the n-th argument pass these values assert addOneSubtractTwo(10) == 9 // Recipe to find text in lines. def findText = { filter, handler, text -> text.eachLine { filter(it) ? handler(it) : null } // Recipe for a regular expression filter. def regexFilter = { pattern, line -> line =~ pattern } // Create filter for searching lines with "Groovy". def groovyFilter = regexFilter.curry(/Groovy/) // Create handler to print out line. def printHandler = { println "Found in line: $it" } // Create specific closure as clone of processText to // search with groovyFilter and print out found lines. def findGroovy = findText.curry(groovyFilter, printHandler) // Invoke the closure. findGroovy('''Groovy rules! And Java? Well... Groovy needs the JVM... ''') // This will output: // Found in line: Groovy rules! // Found in line: Well... Groovy needs the JVM... Zmiękczanie (Currying)

41 Prezentacja przygotowana na podstawie prezentacji z konferencji GR8Conf przeprowadzonej w Kopenhadze w dniach 22-24 Maja 2013 roku, stworzonej przez Huberta Kl’ein Ikkink (aka mrhaki).prezentacji Strona domowa Groovy-iego Opis na anglojęzycznej wikipedi Źródła

42 Koniec


Pobierz ppt "Groovy Dlaczego Groovy jest groovy? Lech Milewski Mail: Skype: lech.milewski.tt."

Podobne prezentacje


Reklamy Google