Fullmenu null

 

20 August 2017

Groovy is like Java, in fact you can use Java code and it will be valid in Groovy. You can declare classes, interfaces, etc but Groovy have some additional functionality and classes that are very useful and less verbose than Java.

One of these additional functionalities is the possibility to create script files that can be executed directly without the compile step. For example you can create utilities for system administrator.

In this post we are ready to create a basic script in which you can appreciate some groovy characteristics that make it special.

Semicolon, parenthesis and more

First famous start Groovy topics is semicolon. Groovy does not need ";" as end line, it is able to deduce it from the context and syntaxt. But if you want you can put it.

When we use a single function on one line, Groovy does not need parentheses, in this way our code is much more readable.

println("no necesito un punto y coma al final")

println "Yo tampoco, ni los parentesis"

Types declaration

Next step will be the type declaration or not (static vs dynamic).

Groovy allow both declaration types and you can declare functions and variables writing data type, but if you use a dynamic declaration your code can be much moore readable and versatile.

When you are not interested in a variable data type (or function return) you can use def, in this way at execution time Groovy look for the methods.

String myString

def unObjeto

unObjeto = "soy un string"

println unObjeto

unObjeto = 10

println unObjeto

Single and double quotation marks

We can declare chains using single or double quotation marks. In this way we can include one of this into other.

If we would use a multi line String we use three double quotation mark to avoid escape character.

println "Necesito una comilla simple ' "
println 'Necesito una comilla doble " '
println """Necesito muchas lineas
donde poder ver los retornos de carro
sin tanto lio como concatenando String """

String vs GString

Groovy adds a GString class that is like a String. When we are using a double quote we are instantiating a GString.

The added value of GString is that we can insert code into a chain that will be evaluate when the variable will be used, in this way we can avoid typical java chain concatenations:

println "Mira lo que puedo hacer ${2+2} simplemente con el dolar y las llaves"

Closure

Before the new Java Lambda implementation, Groovy have the closure concept.

A closure is anonymous piece of code, that is assigned to a variable. A closure can have an input parameter and can be return a value like a functions.

We can invoke that closure with a implicit call(args) method or send it as parameter.

def unaClosure = { param ->
    "${param}".reverse()
}

println unaClosure.call("una cadena")
println unaClosure.call(10)

List, maps and so on

Declaring lists and maps, as well as assigning them is trivial

def lista = [1, 3, 4, "Una cadena", new Date() ]
List otraLista = [1, 3, 4, "Una cadena", new Date() ]

def mapa = [ clave : "valor", otra_clave: "otro valor"]

Loops

Besides the typical for(int i=0; i<10;i++), Groovy offer "each" form in order to visit all list/map elements, one of the most used:

lista.each{ println "it es un objeto de la lista $it"}
mapa.each{ println "it es un Map.Entry $it.key=$it.value" }

If you need know, in each moment, the position you can use "eachWithIndex"

lista.eachWithIndex{ ele, idx ->    //(1)
    println "posicion $idx, elmenento $ele"
}
  1. The closure receives two parameters


Script
println("no necesito un punto y coma al final")

println "Yo tampoco, ni los parentesis"

String myString

def unObjeto

unObjeto = "soy un string"

println unObjeto

unObjeto = 10

println unObjeto

println "Necesito una comilla simple ' "
println 'Necesito una comilla doble " '
println """Necesito muchas lineas
donde poder ver los retornos de carro
sin tanto lio como concatenando String """

println "Mira lo que puedo hacer ${2+2} simplemente con el dolar y las llaves"

def unaClosure = { param ->
    "${param}".reverse()
}

println unaClosure.call("una cadena")
println unaClosure.call(10)

def lista = [1, 3, 4, "Una cadena", new Date() ]
List otraLista = [1, 3, 4, "Una cadena", new Date() ]

def mapa = [ clave : "valor", otra_clave: "otro valor"]

lista.each{ println "it es un objeto de la lista $it"}
mapa.each{ println "it es un Map.Entry $it.key=$it.value" }

lista.eachWithIndex{ ele, idx ->    //(1)
    println "posicion $idx, elmenento $ele"
}