1 / 35

Introducción a

Introducción a. por David Santamaria. http://twitter.com/highwayman d.highwayman@gmail.com http://linkd.in/davidsantamaria. Agenda. ¿Que es Groovy? ¿Por que Groovy? Goodies. Mejoras respecto a Java. Comenzamos. Lenguaje Basicos. ¿Qué es Groovy?.

zarifa
Download Presentation

Introducción a

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introducción a por David Santamaria http://twitter.com/highwayman d.highwayman@gmail.com http://linkd.in/davidsantamaria

  2. Agenda • ¿Que es Groovy? • ¿Por que Groovy? • Goodies. • Mejoras respecto a Java. • Comenzamos. • Lenguaje Basicos.

  3. ¿Qué es Groovy? Groovy es un lenguaje Dinamico para la JVM que permite el uso de caracteristicas de otros lenguajes como Ruby para la comunidad Java. http://groovy.codehaus.org/

  4. ¿Qué mas es Groovy? Groovy también es ... agil, dinamico, compacto, sin curva de aprendizaje, con DSL, soporte de scripts, Totalmente OO, Integrado con Java (Sintaxis Java y Produce Bytecode).

  5. ¿Qué es Groovy? (para los developers) Groovy es un "superset" de Java. Groovy = Java - Boiler Plate Code                 + Dynamic Typing                 + Closures                 + DSL                 + Builders                 + Metaprograming                 + GDK                 - Errores de compilacion                 - Ligeramente mas lento

  6. ¿Por que Groovy? • Java Platform! • Se ejecuta en la JVM (si hay una JVM puedes ejecutar Groovy). • Usa librerias Java. • Embebida en Aplicaciones de Escritorio Java. • Embebida en aplicaciones J2EE • Test con JUnit • Debug con Eclipse, IntelliJ, Netbeans. • Code Coverage con Cobertura. • No requiere aprender nuevas APIS (Jython, JRuby,...) • Rhino es interesante pero es JavaScript :)

  7. Goodies • Tipado Dinamico y estatico. • Totalmente orientado a objetos. (Todo es un Objeto) • Closures. • Sobrecarga de operadores. • Multimethods. • Declaracion Literal de Listas (Arrays), maps, ranges, y expresiones regulares. (Soporte Nativo!) • Metaprogramación. • Y Mas... • GPath. • Builders. • Groovy Beans.

  8. HelloWorld.java public class HelloWorld { public static void main(String[] args){ HelloWorld hw = new HelloWorld(); hw.setNombre("Groovy"); System.out.println(hw.saluda()); } String nombre; public String getNombre() {  return nombre;  } public void setNombre(String nombre) {               this.nombre = nombre;          } public String saluda(){ return "Hola " + nombre;} }

  9. HelloWorld.groovy public class HelloWorld { public static void main(String[] args){ HelloWorld hw = new HelloWorld(); hw.setNombre("Groovy"); System.out.println(hw.saluda()); } String nombre; public String getNombre() {  return nombre;  } public void setNombre(String nombre) {               this.nombre = nombre;          } public String saluda(){ return "Hola " + nombre;} }

  10. HelloWorld.groovy public class HelloWorld { public static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.setNombre("Groovy") System.out.println(hw.saluda()) } String nombre; public String getNombre() {  return nombre } public void setNombre(String nombre) {               this.nombre = nombre         } public String saluda(){ return "Hola " + nombre} } ; opcionales!

  11. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.setNombre("Groovy") System.out.println(hw.saluda()) } String nombre; String getNombre() {  return nombre } void setNombre(String nombre) {               this.nombre = nombre         } String saluda(){ return "Hola " + nombre} } public por defecto!

  12. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.nombre("Groovy") System.out.println(hw.saluda()) } String nombre; String saluda(){ return "Hola " + nombre} } getters and setters autogenerados!

  13. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.nombre("Groovy") System.out.println(hw.saluda()) } String nombre; String saluda(){ "Hola " + nombre} } return opcional!

  14. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.nombre("Groovy") System.out.println(hw.saluda()) } defnombre; def saluda(){ "Hola " + nombre} } Tipado Dinamico!

  15. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.nombre("Groovy") println(hw.saluda()) } def nombre; def saluda(){ "Hola " + nombre} } • Incluido por defecto: • java.io.* • java.lang.* • java.math.BigDecimal • java.math.BigInteger • java.net.* • java.util.* • groovy.lang.* • groovy.util.*

  16. HelloWorld.groovy class HelloWorld { static void main(String[] args){ HelloWorld hw = new HelloWorld() hw.nombre("Groovy") println(hw.saluda()) } def nombre def saluda(){ "Hola ${nombre}" } } GStrings!

  17. HelloWorld.groovy HelloWorld hw = new HelloWorld() hw.nombre("Groovy") println(hw.saluda()) class HelloWorld { def nombre def saluda(){ "Hola ${nombre}" } } Declaracion de clases opcional para Scripts!

  18. HelloWorld.groovy HelloWorld hw = new HelloWorld() hw.nombre "Groovy" println hw.saluda() class HelloWorld { def nombre def saluda(){ "Hola ${nombre}" } } Parentesis opcionales en la mayoria de casos.

  19. HelloWorld.java public class HelloWorld { public static void main(String[] args){ HelloWorld hw = new HelloWorld(); hw.setNombre("Groovy"); System.out.println(hw.saluda()); } String nombre; public String getNombre() {  return nombre;  } public void setNombre(String nombre) {               this.nombre = nombre;          } public String saluda(){ return "Hola " + nombre;} }

  20. HelloWorld.groovy HelloWorld hw = new HelloWorld() hw.nombre "Groovy" println hw.saluda() class HelloWorld { def nombre def saluda(){ "Hola ${nombre}" } }

  21. Comenzamos! • Descargamos la ultima version de Groovy http://groovy.codehaus.org/ • Descomprimimos en un directorio. • Añadimos la variable de entorno GROOVY_HOME. Y %GROOVY_HOME%/bin a la variable PATH. • Escribimos groovy -version

  22. Comenzamos! (II) groovyconsole println "Hola Mundo!" Ctrl + R

  23. Comillas Simples para Strings. Comillas dobles para GStrings: Son como Strings pero soportan expresiones: ${expression}. Strings multi-linea. Lenguaje: Strings and GStrings.

  24. Slashy Strings: Como GStrings  con soporte para Expresiones Regulares. - Muchas mas operaciones... Lenguaje: Strings and GStrings. http://groovy.codehaus.org/Strings+and+GString http://groovy.codehaus.org/JN1525-Strings

  25. Lenguaje: Numbers Java: • Java soporta tipos primitivos y Objetos. • Tiene Wrappers para permitir la conversion. • Java 5+ hay autoboxing /autoUnboxing. Groovy: • Todo es un objeto en el lenguaje. • El realiza el autoboxing cuando es mezclado con Java. • BigDecimal es el tipo por defecto (excepto Integers). • Sobrecarga de operadores. http://groovy.codehaus.org/JN0515-Integers http://groovy.codehaus.org/JN0525-Decimals http://groovy.codehaus.org/JN0535-Floats

  26. Lenguaje: Numbers

  27. Lenguaje: Collections Syntaxis Nativa en colecciones: Java: Groovy: Map map =new HashMap() map.put("nombre","David") map.put("edad",30); map.get("valor"); List list =new ArrayList(     Arrays.asList( "primero","segundo")); list.add("tercero"); def map =[nombre: "David", edad:30] map.valor map["valor"] def list =["primero","segundo"] list <<"tercero"

  28. Lenguaje: Bucles Java: Groovy: for(String s: list){     System.out.println(s); } for(int n=1; n<6; n++){     System.out.println(n); } list.each{     println it } l.upto5,{     println it }

  29. Lenguaje: GDK Java: import java.io.*; public classReadFile { publicstaticvoidmain(String[] args){ try{             BufferedReader br =new BufferedReader( newFileReader( newFile("file.txt")));             String line =null; while((line = br.readLine())!=null){                 System.out.println(line); } }catch(IOException e){             e.printStackTrace(); } } Groovy: newFile(file.txt).echLine{ String line ->     println line }

  30. Lenguaje: Closures Definición de Closures //suma def sum =0 [1,2,3].each{ item -> sum += item } println "Total ${sum}" // listar def text = customers.collect{ item ->      item.name }.join(",") // llamar a un Closure def c ={ name -> println "Hola ${name}"} c("David")

  31. Lenguaje: Closures Iteración en Closures //Simple Loops 5.times{ print it } ->01234 //Strings 'dog'.each{ c -> println c } -> d -> o -> g //Lists and Arrays [1,2,'dog'].each{ print it } ->12dog //Maps ['rod':33,'james':35].each{     print "${it.key}=${it.value} " } -> james=35 rod=33

  32. Lenguaje: GDK • String • contains(), count(), execute(), padLeft(), center(), padRight(), reverse(), tokenize(), each(), etc. • Collection • count(), collect(), join(), each(), reverseEach(), find/All(), min(), max(), inject(), sort(), etc. • File • eachFile(), eachLine(), withPrintWriter(), write(), getText(), etc.

  33. Lenguaje: MarkupBuilder <html> <head> <title>Hola</title> </head> <body> <ul> <li>Mundo 1</li> <li>Mundo 2</li> <li>Mundo 3</li> <li>Mundo 4</li> <li>Mundo 5</li> </ul> </body> </html> import groovy.xml.* def page =new MarkupBuilder() page.html{     head { title 'Hola'}     body{         ul { 1.upto5,{ li "Mundo ${it}"} } } }

  34. Mas Groovy - Groovy Doc: http://groovy.codehaus.org/ - Groovy Koans: https://github.com/cjudd/groovy_koans

  35. Preguntas...

More Related