Temporada 0 Episodio 1: Ciclos en Groovy y Colecciones

Domingo Suarez Torres

grails.org.mx Screencast.

Temporada 0 Episodio 1: Ciclos en Groovy y Colecciones

grails.org.mx Screencast.

Hola, ¿qué tal? Bienvenidos al Screencast, episodio número uno de la temporada cero de Grevis.org.mx.

Hello, how are you? Welcome to the Screencast, episode number one of season zero of Grevis.org.mx.

Mi nombre es Domingo Suárez y, pues bueno, en esta ocasión vamos a mostrar algunos de los conceptos básicos de Groovy.

My name is Domingo Suárez and, well, this time we are going to show some of the basic concepts of Groovy.

Espero esto se complemente con el Screencast anterior para que quede un poquito más claro algunas de las cosas que hace Groovy.

I hope this complements the previous screencast to make some of the things Groovy does a little clearer.

Muy bien, vamos a empezar por escribir en un editor de texto nuestro primer script de Groovy o nuestra primer clase de Groovy,

Very well, let's start by writing our first Groovy script or our first Groovy class in a text editor.

que en este caso se va a llamar básicos.groovy. ¿Qué ocurre con esta clase básicos Groovy?

which in this case will be called basics.groovy. What happens with this basics Groovy class?

Muy bien, lo que vamos a hacer con esta clase es que nos va a servir para ir mostrando algunas de las características interesantes.

Very well, what we are going to do with this class is that it will help us to show some interesting features.

Antes de Groovy, la clase, el Screencast pasado, nosotros hicimos algo así, hola mundo desde Groovy

Before Groovy, in the last Screencast, we did something like this, hello world from Groovy.

y lo único que hacíamos acá era decirle Groovy, el nombre del código Groovy y obviamente imprimir esto en la consola, ¿no?

And the only thing we did here was to tell it Groovy, the code name Groovy, and obviously print this to the console, right?

Pero, ¿realmente esto cómo es posible que funcione? Si todo en Java, a final de cuentas, este código Groovy se convierte en bytecode,

But, how is it possible for this to work? If everything in Java, in the end, this Groovy code is converted into bytecode,

¿cómo funciona esto?

How does this work?

¿Cómo realmente funciona esto?

How does this really work?

Bueno, algo muy sencillo y para esto vamos a ocupar el compilador de Groovy.

Well, something very simple and for this we are going to use the Groovy compiler.

Recuerden que es el Groovy C, Groovy Compiler.

Remember that it's the Groovy C, Groovy Compiler.

Lo que vamos a hacer es compilar la clase Groovy para que nos genere el punto class

What we are going to do is compile the Groovy class so that it generates the class file.

y luego vamos a analizar ese punto class para ver qué fue lo que ocurrió.

And then we are going to analyze that class point to see what happened.

Bueno, obviamente vamos a ocupar la herramienta Java P.

Well, obviously we are going to use the Java P tool.

Y esta nos va a dar la clave de qué es lo que está pasando.

And this is going to give us the key to what is happening.

Esta clase, básicos.groovy, se está convirtiendo en una clase que extiende de una clase de Groovy que se llama script.

This class, basics.groovy, is becoming a class that extends from a Groovy class called script.

Aquí la podemos ver.

Here we can see it.

Lo padre de eso es que nosotros simplemente lo único que tuvimos que hacer fue solamente escribir el código de nuestro script

The cool thing about that is that all we had to do was just write the code for our script.

y Groovy de manera automática construye una clase.

And Groovy automatically builds a class.

Obviamente Groovy detecta que no tiene definición.

Obviously, Groovy detects that it has no definition.

Definición de clase y como funciona Groovy es que de manera automática genera una clase que extiende de script

The definition of a class and how Groovy works is that it automatically generates a class that extends from script.

e implementa el método main y dentro del método main pues mete el código que nosotros hayamos escrito aquí.

And implement the main method and inside the main method, include the code that we have written here.

Entonces, pues bueno, eso es solamente para aclarar cómo funciona esto.

So, well, that's just to clarify how this works.

Muy bien, vamos a empezar con otras cosas interesantes con respecto a Groovy.

Very well, let's start with other interesting things regarding Groovy.

Bueno, esto nada más es para que veamos la utilidad de Java.

Well, this is just to show us the usefulness of Java.

AP no sirve para ver o analizar todos los métodos que define una clase, ¿no?

AP is not useful for viewing or analyzing all the methods defined in a class, right?

Pero bueno, muy bien.

But well, very good.

¿Con qué vamos a seguir a continuación?

What are we going to continue with next?

Bueno, vamos a ver cómo se hacen bucles en Groovy, ¿no?

Well, let's see how to create loops in Groovy, shall we?

Primero vamos a hacerlo de la manera Java.

First, let's do it the Java way.

Ciclos a la Java.

Cycles to Java.

Muy bien.

Very good.

¿Cómo se hace un ciclo a la Java, por ejemplo?

How do you create a loop in Java, for example?

Lo clásico.

The classic.

¿No?

Not?

int i igual a cero.

int i equal to zero.

i menor a diez, por ejemplo.

it is less than ten, for example.

Perdón.

Sorry.

Menor a diez.

Less than ten.

I.

I.

Incrementamos el contador.

We increased the counter.

Y vamos a imprimir en la consola.

And we are going to print in the console.

Iterando.

Iterating.

Más i, por ejemplo.

More i, for example.

Lo que vamos a ver en la salida.

What we are going to see in the output.

En la consola, pues, es este, ah, lo estoy compilando, perdón, no es compilando, es con el intérprete, ¿no?

In the console, well, this is it, ah, I'm compiling, sorry, it's not compiling, it's with the interpreter, right?

O aquí vemos la salida del programa.

Or here we see the program's output.

Hay una manera un poquito de hacerlo esto a la manera Groovy.

There's a slightly groovy way to do this.

Hay una diferencia muy importante si yo pongo una cadena con comillas simple.

There is a very important difference if I put a string with single quotes.

Si la hago con comilla doble, lo que hago es convertir esta cadena en un GString.

If I do it with double quotes, what I do is convert this string into a GString.

Un GString.

A G-string.

Y me permite hacer interpolación de variables, por ejemplo.

And it allows me to interpolate variables, for example.

Y vean lo que ocurre a continuación.

And see what happens next.

Voy a limpiar la pantalla.

I'm going to clean the screen.

Y ejecutar el intérprete de Groovy.

And run the Groovy interpreter.

Y vean, obtengo el mismo resultado, solamente que ya no tuve que hacer la concatenación.

And look, I get the same result, except that I didn't have to do the concatenation anymore.

De todos modos ocurre de una manera óptima con Groovy, pero ya no lo tuve que hacer yo.

Anyway, it occurs in an optimal way with Groovy, but I no longer had to do it myself.

A mí me gusta mucho hacer interpolación de variables.

I really enjoy doing variable interpolation.

¿De dónde viene este i?

Where does this i come from?

Pues, bueno, está declarado dentro del form.

Well, it is stated in the form.

¿Cómo podemos hacer este ciclo un poquito más sencillo y más a la forma Groovy?

How can we make this cycle a little simpler and more Groovy?

Bueno, se hace muy sencillo.

Well, it becomes very easy.

Por ejemplo, le digo 10 veces.

For example, I tell him 10 times.

Ahorita voy a explicar qué demonios estoy haciendo.

Right now I'm going to explain what the hell I'm doing.

Y vean, ciclos a la Groovy se comporta exactamente igual que ciclos a la Java.

And look, Groovy loops behave exactly the same as Java loops.

Con la gran diferencia de que la estructura fue un poquito más sencilla de escribir.

With the big difference that the structure was a little easier to write.

Solamente tuve que decirle 10 veces quiero que hagas esto.

I only had to tell him 10 times I want you to do this.

Ahora, ¿qué es lo que está ocurriendo aquí?

Now, what is happening here?

Yo tengo 10.

I have 10.

Yo podría pensar que 10 es el número primitivo, pero no.

I could think that 10 is the primitive number, but no.

Por ejemplo, yo para validar esto, println10.class.name.

For example, I use println10.class.name to validate this.

Vamos a ver qué ocurre.

Let's see what happens.

Vean cómo ese número 10 es un java.lang.integer.

See how that number 10 is a java.lang.integer.

Realmente es una clase de Java.

It is really a Java class.

Voy a omitir ahorita el código de ciclos a la Java.

I am going to omit the Java-style loop code right now.

Para que no me esté generando salida a la consola de más.

So that it doesn't generate extra output to the console for me.

Y pues, bueno, eso también lo voy a quitar.

And well, I'm going to remove that too.

En el código que voy a dejarles disponibles, ahí sí va a estar completo para que lo usen.

In the code that I am going to make available to you, it will be complete for you to use.

Ok, entonces podemos ver que este 10 realmente es un...

Okay, so we can see that this 10 is really a...

Objeto en Groovy, todo es un objeto y aquí lo podemos constatar.

Object in Groovy, everything is an object and we can confirm it here.

Ahora, algo muy interesante.

Now, something very interesting.

Este times es realmente un método.

This times is really a method.

Un método que existe en la clase java.lang.integer.

A method that exists in the class java.lang.Integer.

El detalle es que ese método, si ustedes lo buscan en el javadoc, no lo van a encontrar.

The detail is that this method, if you look for it in the javadoc, you will not find it.

Es un método agregado por el gdk.

It is a method added by the gdk.

Ok.

Okay.

En un futuro screencast.

In a future screencast.

Voy a explicar qué es el gdk.

I am going to explain what the gdk is.

Pero de entrada, yo lo que les puedo decir es que el gdk son mejoras a las clases existentes de la librería estándar.

But to begin with, what I can tell you is that the gdk is an enhancement to the existing classes of the standard library.

Ok.

Ok.

Realmente lo que ocurre es que Groovy...

What really happens is that Groovy...

En el momento en que se levanta, va a inyectar código.

At the moment he gets up, he is going to inject code.

Va a inyectarle métodos a las clases existentes de java y eso es conocido como el gdk.

It will inject methods into the existing Java classes, and that is known as the GDK.

Y luego, ¿qué más está ocurriendo?

And then, what else is happening?

Este cacho que yo estoy seleccionando aquí es un cacho o un bloque de código.

This piece that I am selecting here is a piece or a block of code.

Ese cacho o bloque de código...

That piece or block of code...

Son los llamados closures.

They are called closures.

Bloques o pedazos de código.

Blocks or pieces of code.

Tienen muchas características importantes.

They have many important characteristics.

Pero por el momento...

But for the moment...

No voy a mencionarlas porque me podría llevar...

I'm not going to mention them because it could take me...

De hecho, me voy a llevar todo un screencast explicando y usando la parte de los closures.

In fact, I am going to take a whole screencast explaining and using the part about closures.

Por el momento, lo que nos conviene entender es que el times...

For the moment, what we need to understand is that the times...

Número uno, 10, es una clase integer, no es un primitivo.

Number one, 10, is an integer class, it is not a primitive.

Times es un método que existe definido en la clase integer inyectado en tiempo de ejecución por el gdk.

Times is a method that exists defined in the integer class injected at runtime by the gdk.

Y que recibe como parámetro un pedazo de código, que es un closure.

And it receives as a parameter a piece of code, which is a closure.

Y este...

And this...

Entonces nos sirve perfecto para hacer ciclos, por ejemplo.

So it works perfectly for making cycles, for example.

Y de una manera muy sencilla.

And in a very simple way.

De hecho, me encanta la sintaxis porque se lee 10 veces.

In fact, I love the syntax because it is read 10 times.

Haz esta instrucción.

Follow this instruction.

Y eso es fabuloso.

And that is fabulous.

Muy bien.

Very good.

¿De qué otra manera podríamos hacer ciclos en Java?

What other ways could we create loops in Java?

Perdón, en Groovy.

Sorry, in Groovy.

Yo podría decirle...

I could tell you...

10 up to...

10 hasta...

Perdón, de 0 a 10 veces.

Sorry, from 0 to 10 times.

Quiero que hagas...

I want you to do...

Este otro cacho de código.

This other piece of code.

Ah, se me olvidó explicar algo.

Ah, I forgot to explain something.

De hecho, aquí lo voy a poner como comentario.

In fact, I’m going to post it here as a comment.

It es un parámetro que de manera implícita Groovy nos envía.

It is a parameter that Groovy implicitly sends us.

Que implícitamente Groovy nos envía en...

That implicitly Groovy sends us in...

Y es un parámetro que...

And it is a parameter that...

Y esto lo voy a poner con mayúscula.

AND I'M GOING TO WRITE THIS IN CAPITAL LETTERS.

Todos los closures.

All the closures.

Eso es muy, muy importante que lo sepamos y que existe.

It is very, very important that we know it and that it exists.

¿Por qué ocurre así?

Why does it happen this way?

¿O por qué está de esta manera?

Or why is it this way?

Pues bueno, en este caso, como podremos ver,

Well then, in this case, as we will see,

IT nos sirvió para saber en qué parte del ciclo estábamos.

It helped us to know what part of the cycle we were in.

¿Ok?

Okay?

De igual manera acá, esto es un closure.

Similarly here, this is a closure.

Groovy nos va a mandar ese parámetro.

Groovy is going to send us that parameter.

Pero nosotros podríamos cambiar...

But we could change...

El valor por un nombre que nosotros querramos.

The value for a name that we want.

Cuando yo escribo guión mayor que,

When I write a greater than sign,

lo que hago es separar los parámetros del código.

What I do is separate the parameters from the code.

¿De acuerdo?

Okay?

Entonces, aquí voy a poner un pequeño comentario.

So, here I am going to put a small comment.

Que diga el operador...

Let the operator say...

Pulano.

So-and-so.

Pulano sirve para separar...

Pigman is used to separate...

Los parámetros del closure del código.

The parameters of the code closure.

¿Sale?

Are we good?

Para eso nos sirve.

That's what it's for.

Si nosotros no ponemos esto, vamos a obtener algún error.

If we don't put this in, we are going to get some error.

Muy bien.

Very good.

Y yo podría aquí utilizar valor, por ejemplo.

And I could use courage here, for example.

Entonces, esto me sirve para que cuando yo quiera...

So, this helps me so that when I want...

Cambiar el nombre del parámetro que Groovy de manera implícita me envía.

Change the name of the parameter that Groovy implicitly sends me.

De manera explícita yo le digo cómo quiero que se llame.

I explicitly tell him how I want him to be called.

Y...

And...

Corro esto.

I run this.

Y ahora vean la gran diferencia entre Times, entre Optu.

And now see the big difference between Times, between Optu.

Es que Times incluye el...

It's just that Times includes the...

El...

The...

Número por el cual empieza.

Number by which it starts.

Y el número hasta el cual termina.

And the number up to which it ends.

Por lo tanto...

Therefore...

Hace 11 iteraciones.

Make 11 iterations.

Eso es muy importante que lo sepamos.

It is very important that we know that.

Muy bien.

Very well.

Porque va del 0 al 10.

Because it goes from 0 to 10.

Y por el otro lado, Times empieza en el 0 y termina en el 9.

And on the other side, Times starts at 0 and ends at 9.

Porque realmente solamente...

Because really only...

Bueno, lo hacen.

Well, they do.

Nada más 10 veces.

Nothing more than 10 times.

Es una gran diferencia entre Optu y Times.

There is a big difference between Optu and Times.

Obviamente, por ejemplo, yo podría definir...

Obviously, for example, I could define...

Yo podría decir...

I could say...

Def...

Def...

Inicio igual a 0.

Start equal to 0.

Y...

And...

Término igual a 10.

Term equal to 10.

Yo podría hacer aquí esto.

I could do this here.

Término...

Term...

Inicio.

Start.

Y esto va a funcionar exactamente igual.

And this is going to work exactly the same.

Voy a poner aquí un ciclo.

I am going to put a cycle here.

Ciclos a la Groovy.

Groovy cycles.

Con Optu.

With Optu.

Corro esto.

I run this.

Y bueno, vean la salida, ¿no?

And well, look at the exit, right?

Obviamente funciona con variables.

It obviously works with variables.

Y eso también le brinda mucha funcionalidad.

And that also provides a lot of functionality.

Otra de las cosas interesantes es que, por ejemplo, el inicio puede ser, por ejemplo, 7.

Another interesting thing is that, for example, the start can be, for example, 7.

Y esto sigue funcionando de la misma manera.

And this continues to work in the same way.

Obviamente nada más que del 7 en adelante.

Obviously nothing but from 7 onwards.

Muy bien.

Very well.

Bien.

Good.

Existe otro...

There is another...

Otro tipo de ciclo que yo puedo ocupar, que es el Step.

Another type of cycle that I can use is the Step.

Y eso está muy interesante porque yo puedo decirle...

And that is very interesting because I can tell you...

Empieza en el 5.

Start at 5.

Y vas saltándote hasta el número 10 de 2 en 2, por ejemplo.

And you skip to number 10 in increments of 2, for example.

Y le digo...

And I tell him...

Iterando IT con Step.

Iterating IT with Step.

Y vamos a ver qué ocurre.

And let's see what happens.

Vean cómo empieza en el 5.

Look how it starts at 5.

Luego le dije que se tenía que ir de 2 en 2.

Then I told him that he had to leave in pairs of two.

¿Sale?

Are you leaving?

Le dije que se fuera de 2 en 2.

I told him to leave in pairs of two.

Entonces va 5, 7 y 9.

So it goes 5, 7, and 9.

Y obviamente ya no toca el 10 porque...

And obviously he doesn't play the 10 anymore because...

Obviamente ya no quedan, digamos, en su rango de pasos.

Obviously, they no longer fall within their range of steps.

Entonces este Step también es muy interesante.

So this Step is also very interesting.

En Java no existe algo similar que yo conozca.

In Java, there is nothing similar that I know of.

Se podría emular con un Continue.

It could be emulated with a Continue.

Solamente.

Only.

Pero bueno, no existe algo similar en Java.

Well, there is nothing similar in Java.

Muy bien.

Very well.

Esas son algunas de las maneras en las cuales ustedes pueden hacer bucles a la Groovy.

Those are some of the ways in which you can create loops in Groovy.

Obviamente ustedes pueden seguir ocupando el While.

Obviously, you can continue using the While.

Eso sigue funcionando sin ningún problema.

That is still working without any problems.

Pero, pues bueno, la intención era mostrarles los ciclos a la Groovy.

But, well, the intention was to show you the cycles in Groovy.

Muy bien.

Very well.

Vamos a empezar con un tema bastante interesante que a mí me gusta mucho, que son las colecciones.

Let's start with a quite interesting topic that I really like, which is collections.

Las colecciones, pues obviamente en Java tenemos...

The collections, well obviously in Java we have...

Mapas, por ejemplo.

Maps, for example.

Mapas, listas y arreglos, ¿no?

Maps, lists, and arrangements, right?

Entre ellas.

Among them.

Por lo tanto, en Groovy también tenemos soporte para estas.

Therefore, in Groovy we also have support for these.

Pero Groovy va a agregar algo llamado azúcar sintáctica para que podamos nosotros declarar mapas y listas de una manera más sencilla, ¿no?

But Groovy is going to add something called syntactic sugar so that we can declare maps and lists in a simpler way, right?

Y para ello vamos a empezar por la más rara y la más interesante.

And for that, we are going to start with the strangest and the most interesting.

Como había mencionado, Java soporta mapas, listas y arreglos.

As I mentioned, Java supports maps, lists, and arrays.

Pero hay una estructura o una colección muy interesante que son los rangos.

But there is a very interesting structure or collection that are the ranks.

Muy bien.

Very well.

¿Qué es un rango?

What is a range?

Muy bien.

Very well.

Un rango puede ser un número que va del 0.

A range can be a number that goes from 0.

Vamos a ponerle del 10.

We are going to give it a 10.

Perdón.

Sorry.

Un rango es igual del 10 hasta el 50.

A range is from 10 to 50.

Puedo definir un rango.

I can define a range.

Rango alfa.

Alpha range.

Fragmentico.

Fragmented.

Que va de la A a la Z.

It goes from A to Z.

Ok.

Ok.

Interesante, ¿no?

Interesting, isn't it?

Pero digo, ¿qué podría hacer con estos rangos?

But I say, what could I do with these ranges?

Por ejemplo, yo podría hacer un bucle for.

For example, I could do a for loop.

For.

For.

Elemento.

Element.

Es el número que yo le quiero poner.

It's the number that I want to give it.

Se puede llamar como yo quiera.

It can be called whatever I want.

Println.

Println.

Item.

Item.

Por ejemplo.

For example.

Voy a ver qué ocurre con esto.

I’m going to see what happens with this.

Y ahí está la salida.

And there is the exit.

Bueno, fueron demasiados números.

Well, that was too many numbers.

Vamos a ponerle hasta el 20.

Let's put it up to 20.

De 10 a 20.

From 10 to 20.

Y bueno, aquí está, ¿no?

Well, here it is, right?

Se va del 10 hasta el número 20.

It goes from 10 to number 20.

Como podrán ver, es inclusivo.

As you can see, it is inclusive.

Desde el número inferior.

From the lower number.

Bueno, desde el elemento inicial al elemento final.

Well, from the initial element to the final element.

Por lo tanto, aquí hay.

Therefore, here it is.

11 elementos en vez de 10.

11 elements instead of 10.

Entonces, ahí hay que tener cuidado, ¿no?

So, we have to be careful there, right?

Este rango, por ejemplo, yo podría cambiar aquí.

For example, I could change this range here.

Por rango alfabético.

By alphabetical order.

Vamos a ver qué ocurre.

Let's see what happens.

Entonces, pues me imprimió el abecedario.

So, he printed the alphabet for me.

Entonces, pues bueno, es una manera.

So, well, it's one way.

Es padre de tener colecciones de objetos.

It's great to have collections of objects.

En una estructura llamado rangos.

In a structure called ranges.

Rangos.

Ranks.

Bastante interesante.

Quite interesting.

Pero realmente, ¿qué son estos rangos?

But really, what are these ranks?

Estos rangos, pues vamos a ver de qué se tratan.

Let's see what these ranges are about.

O cómo se comen, ¿no?

Or how do you eat them, right?

¿Cómo lo podemos hacer?

How can we do it?

Bueno, pues vamos a imprimir qué clases son, ¿no?

Well, let's print out what classes they are, right?

Rango.class.name.

Rango.class.name.

¿De acuerdo?

Okay?

Y luego vamos a hacer lo mismo.

And then we are going to do the same.

Con el rango alfabético.

With the alphabetical range.

Muy bien.

Very well.

Y vamos a ver qué ocurre.

And let's see what happens.

Como podríamos ver, el primer rango, como es de números, pues es un rango de enteros.

As we could see, the first range, since it consists of numbers, is a range of integers.

Y el segundo rango, como es un rango de letras, pues me pone que es un rango de objetos.

And the second range, since it is a range of letters, tells me that it is a range of objects.

Entonces, digamos que Groovy nos va a permitir, por ejemplo, hacer rangos de nuestros objetos personalizados.

So, let's say that Groovy will allow us, for example, to create ranges of our custom objects.

Creo que es solamente necesario implementar Comparable para que se pueda hacer un rango de letras.

I think it is only necessary to implement Comparable so that a range of letters can be made.

Que estos puedan estar ordenados como tal cual nosotros lo tenemos definido aquí.

That these may be arranged as we have defined them here.

Entonces, pues bueno, como verán, no inventa Groovy nada nuevo.

Well, as you can see, Groovy doesn't invent anything new.

Simplemente utiliza lo que existe en la plataforma Java.

Just use what exists on the Java platform.

Y lo mejora, como en este caso, rangos que no existe.

And it improves it, as in this case, ranges that do not exist.

Este tipo de colección en Java de manera nativa.

This type of collection in Java natively.

Muy bien.

Very well.

Podemos hacer rangos muy marihuanos o muy interesantes como este.

We can make very laid-back or very interesting rankings like this one.

Voy a definir una variable que se llame hoy.

I am going to define a variable called today.

Que sea de tipo fecha.

It should be of date type.

Algo interesante que no he mencionado en este momento es que, y aquí lo voy a poner como comentario.

Something interesting that I haven't mentioned at this moment is that, and here I will put it as a comment.

Groovy automáticamente importa los paquetes JavaUtil, JavaMath, JavaIO, GroovyLang y GroovyUtil, entre otros.

Groovy automatically imports the JavaUtil, JavaMath, JavaIO, GroovyLang, and GroovyUtil packages, among others.

Por lo tanto, no es necesario importar el paquete, o perdón, sí, el paquete útil, que es donde está definido.

Therefore, it is not necessary to import the package, or sorry, yes, the useful package, which is where it is defined.

La clase Date, ¿de acuerdo?

The Date class, okay?

Bien.

Good.

Acabo de definir una fecha, la fecha del día de hoy.

I just set a date, today's date.

Voy a definir la fecha de ayer.

I am going to define yesterday's date.

Y esto es algo que me gusta mucho.

And this is something that I really like.

Hoy menos un día.

Today minus one day.

Sale.

Okay.

Ayer antier igual a ayer menos uno.

The day before yesterday is the same as yesterday minus one.

Y mañana, voy a definir mañana.

And tomorrow, I will define tomorrow.

Que sea hoy más uno.

Let it be one more today.

¿De acuerdo?

Are we agreed?

Y luego, voy a definir un rango de fechas que sea de antier hasta mañana.

And then, I am going to define a date range that goes from the day before yesterday until tomorrow.

Y luego vamos a imprimir esto.

And then we are going to print this.

PrintLine.

PrintLine.

Además, vamos a imprimirlo también en un bucle para que veamos cómo se compone.

Furthermore, we will also print it in a loop so that we can see how it is composed.

Nota.

Note.

Sale.

Okay.

Rango fechas.

Date range.

Sale.

Okay.

Vamos a ver qué ocurre.

Let's see what happens.

Y aquí está.

And here it is.

Bueno, antier fue 25 de enero.

Well, the day before yesterday was January 25th.

Ayer fue 26.

Yesterday was the 26th.

Hoy es 27 de enero.

Today is January 27th.

Aquí lo podemos ver, 27 de enero.

Here we can see it, January 27th.

Y mañana es 28 de enero.

And tomorrow is January 28th.

Está padre esto de los rangos.

This ranking thing is cool.

No nos puede, por ejemplo, servir para definir rangos de fechas laborables.

It cannot help us, for example, to define ranges of working dates.

O de vacaciones.

Or on vacation.

No lo sé.

I don't know.

Nos puede servir para muchísimas cosas.

It can help us with a lot of things.

Muy bien.

Very well.

¿Qué más podemos hacer con los rangos?

What else can we do with the ranks?

Bueno, creo que con los rangos es básicamente lo que quería mostrarles el día de hoy.

Well, I think that's basically what I wanted to show you today regarding the ranks.

De hecho, hay otra manera de hacer bucles.

In fact, there is another way to create loops.

Vamos a intentarlo.

Let's give it a try.

Rango de fechas.

Date range.

Punto each.

Point each.

Ajá.

Aha.

Creo que sí funciona.

I believe it does work.

Ah, perdón, me equivoqué.

Ah, sorry, I made a mistake.

Each.

Each.

Y aquí le podemos poner.

And here we can put it.

Vamos a borrar este.

Let's delete this.

For.

For.

Sale.

Deal.

Y vamos a correr de nuevo esto.

And we're going to run this again.

Ah, perdón.

Ah, sorry.

Este no es item, es it.

This is not an item, it is it.

Obvio.

Obvious.

Me equivoqué.

I was wrong.

Ahí está.

There it is.

Entonces, esta es otra manera.

So, this is another way.

Esta es otra manera de hacer bucles.

This is another way to create loops.

Obviamente, el each, o el método each en las colecciones, sirve solamente para colecciones, ¿sale?

Obviously, the each method in collections is only for collections, right?

O para...

Or to...

Bueno, nos puede servir para las diversas colecciones que nos podemos ocupar.

Well, it can help us with the various collections we can take on.

En este caso, para colecciones.

In this case, for collections.

Perdón, para rangos.

Sorry, for rankings.

¿Qué otro tipo de cosas podemos hacer con los rangos?

What other types of things can we do with ranges?

Bueno, creo que es lo que quería mostrar.

Well, I think that's what I wanted to show.

Y vamos a continuar con...

And we are going to continue with...

Los mapas.

The maps.

Perdón, con las listas primero.

Sorry, with the lists first.

Listas en Groovy.

Lists in Groovy.

¿De acuerdo?

Are you okay with that?

En Java, ¿cómo hacemos una lista?

In Java, how do we create a list?

Le decimos...

We say...

Lista...

List...

Java igual new array list.

Java equals new array list.

Por ejemplo.

For example.

Y luego, si queremos agregar elementos a la lista, tenemos que mandar ya el método add.

And then, if we want to add elements to the list, we have to use the add method.

Por ejemplo.

For example.

Para cada uno de los elementos que...

For each of the elements that...

Querramos agregar a la lista.

We want to add to the list.

Println.

Println.

Lista.

List.

Java.

Java.

¿Ok?

Okay?

Si esto lo corremos, vamos a ver que nos imprime aquí la lista, ¿no?

If we run this, we will see what it prints the list here, right?

Con el elemento 1 y el elemento 2.

With element 1 and element 2.

Muy bien.

Very well.

¿Cómo se hace esto?

How is this done?

¿O cómo definimos listas en Groovy?

Or how do we define lists in Groovy?

De una manera sencilla.

In a simple way.

Bueno, vamos a verlo.

Well, let's see.

Def.

Def.

Lista.

List.

Igual.

Same.

Y esto me fascina porque es muy sencillo.

And this fascinates me because it is very simple.

Declarar listas.

Declare lists.

Uno.

One.

Dos.

Two.

Prácticamente en una sola línea, nosotros estamos declarando.

Practically in a single line, we are declaring.

Tanto la lista como los elementos que van dentro de ella.

Both the list and the elements that go inside it.

¿Ven?

Do you see?

Esto está bastante interesante y bastante padre.

This is quite interesting and really cool.

Porque nos brinda muchísima facilidad, ¿no?

Because it provides us with a lot of ease, right?

Si nosotros comparamos este código contra este, pues vemos que es más sencillo.

If we compare this code against this one, we see that it is simpler.

Obviamente para un desarrollador Java que recién comienza en Groovy.

Obviously for a Java developer who is just starting out with Groovy.

Pues va a encontrar esta sintaxis un poco rara.

Well, you are going to find this syntax a bit strange.

Pero ya una vez que te familiarices con ella, pues es bastante fácil.

But once you become familiar with it, it's quite easy.

Muy bien.

Very well.

Y obviamente nosotros podemos hacer un...

And obviously we can make a...

Podemos imprimir en la consola el contenido de esa lista, ¿no?

We can print the content of that list to the console, right?

Ahora, si yo voy a la lista.

Now, if I go to the list.

A la lista Java.

To the Java list.

Y le pido su clase.

And I ask for your class.

Y a su clase le digo...

And to your class, I say...

Le pido el nombre.

I ask for your name.

¿De acuerdo?

Okay?

Voy a obtener lo que yo espero que sea esto.

I am going to get what I hope this will be.

De hecho, vamos a ver qué ocurre.

In fact, let's see what happens.

Pero lo que yo espero de esto es que esto sea de tipo ArrayList.

But what I expect from this is for it to be of type ArrayList.

¿Están de acuerdo?

Do you agree?

Porque es la clase que yo estoy instanciando.

Because it's the class that I am instantiating.

En el caso de acá, yo no le estoy diciendo qué clase es.

In this case, I am not telling him what class it is.

Pero Groovy, como es muy inteligente y obviamente estoy ocupando los operadores.

But Groovy, since it is very intelligent and I am obviously using the operators.

Pero es pertinentes.

But it is relevant.

Groovy va a escoger la implementación adecuada para declarar las listas.

Groovy is going to choose the appropriate implementation to declare the lists.

Y si no me creen, bueno, para eso acabo de hacer lo siguiente.

And if you don't believe me, well, that's why I just did the following.

Vamos a ver qué ocurre.

Let's see what happens.

Vean cómo la clase del ArrayList que yo declaré, pues es precisamente el ArrayList.

Look at how the ArrayList class that I declared is precisely the ArrayList.

Y la clase de la lista que me creó Groovy es también un ArrayList.

And the class of the list that Groovy created for me is also an ArrayList.

Entonces esto sigue siendo totalmente Java.

So this is still totally Java.

Muy bien.

Very well.

Como les mencionaba, pues bueno, podemos hacer este uso del operador each para iterar cada uno de los elementos, ¿no?

As I was mentioning, well, we can use the each operator to iterate over each of the elements, right?

Y decirle println it.

And tell it println it.

Y pues esto funciona exactamente igual que funciona con los rangos.

And this works exactly the same way as it does with the ranks.

¿Sale?

Does it work?

Muy bien.

Very well.

Vamos a continuar con los mapas.

Let's continue with the maps.

Los mapas son cosa seria.

Maps are serious business.

Print, line, mapas.

Print, line, maps.

Muy bien.

Very well.

¿Cómo hacemos mapas en Java?

How do we make maps in Java?

Bueno, lo hacemos así.

Well, we’ll do it this way.

Mapa Java igual a, igual, bueno, new.

Map Java equal to, equal, good, new.

Voy a hacer un hash map, por ejemplo, y ya.

I'm going to make a hash map, for example, and that's it.

Si yo quiero poner un elemento al mapa, pues tengo que escribir mapa, perdón, mapa Java, punto put.

If I want to add an element to the map, then I have to write map, sorry, Java map, dot put.

Y tengo que decirle la llave, coma, y el valor, por ejemplo.

And I have to tell you the key, comma, and the value, for example.

Entonces, bueno, voy a agregar dos elementos solamente para hacerlo rápido.

So, well, I'm going to add two elements just to make it quick.

Y lo puedo imprimir en consola.

And I can print it on the console.

Ok, mapa Java.

Ok, Java map.

Listo.

Ready.

Vamos a ver que imprime en consola esto.

Let's see what this prints in the console.

Pues aquí está, ¿no?

Well, here it is, right?

Mapas, llave, dos...

Maps, key, two...

llave, dos puntos valor, llave, dos puntos valor

key, colon value, key, colon value

muy bien, es lo que tenemos

very well, it is what we have

¿cómo hacemos

How do we do it?

esto a la manera groovy?

Is this in a groovy way?

println

println

mapa

map

a la groovy, ¿cómo hacemos esto a la manera

in a groovy way, how do we do this our way?

groovy? muy sencillo, mapa

groovy? very simple, map

igual, estamos exactamente

same, we are exactly

bueno, casi la misma sintaxis que para

Well, almost the same syntax as for

declarar listas, con la gran diferencia

declare lists, with the great difference

de que yo voy a declarar

that I am going to declare

cada vez que quiera

whenever I want

agregar un elemento al mapa, le digo

add an element to the map, I tell him/her.

la llave, dos puntos

the key, colon

valor

value

llave

key

dos puntos valor

colon value

llave

key

dos puntos

two points

valor

value

ok

ok

y luego ¿qué ocurre aquí?

and then what happens here?

aquí

here

println

println

mapa

map

muy bien

very good

voy a ver que ocurre

I will see what happens.

en la consola con esto

in the console with this

vamos a ver que me está imprimiendo

Let's see what it is printing for me.

más o menos lo mismo, obviamente

more or less the same, obviously

cambié los valores, pero fue exactamente

I changed the values, but it was exactly.

lo mismo, ahora

the same, now

¿qué ocurre si yo

What happens if I

quiero saber, al igual que en la lista

I want to know, just like in the list.

en la lista yo para obtener

on the list I to obtain

la clase y el nombre de la clase

the class and the name of the class

lo que hice fue decirle

What I did was tell him/her.

nombre de

name of

en este caso nombre del mapa, dame la clase

In this case, the name of the map, give me the class.

y luego dame el nombre

and then give me the name

esto no va a funcionar

this is not going to work

y vamos a ver que va a tronar como chinampina

and let's see what's going to crack like a chinampina

porque

because

me está diciendo

he is telling me

me está mandando null pointer exception

It is giving me a null pointer exception.

me dice no puedo obtener la propiedad name

It tells me I can't get the property name.

en un objeto nulo

in a null object

híjole, y aquí ¿qué rayos pasó?

Wow, and what the heck happened here?

bueno, con los mapas hay algo muy

Well, with the maps there is something very

curioso, que es que

curious, what is it that

yo por ejemplo, yo puedo

I, for example, I can.

acceder a un mapa de diversas

access a map of various

maneras, a sus elementos, vaya

ways, to its elements, go ahead

yo puedo decirle

I can tell you.

mapa-llava.llave1

map-key.key1

.llave1

.key1

sale, voy a comentar un momento

Okay, I'm going to comment for a moment.

la línea de abajo

the bottom line

voy a correr de nuevo mi

I'm going to run again my

programa, y vamos

program, and let's go

a ver

let's see

¿qué pasó aquí?

What happened here?

a ver, a ver, a ver

let's see, let's see, let's see

¿qué pasó aquí?

What happened here?

llave1

key1

llave1, mapa-llava

key1, map-key

.llave1

.key1

no lo guardé, está sin guardar

I didn't save it, it's unsaved.

perdón

sorry

ahí está

there it is

vean como

see how

cuando yo quiero acceder al elemento de un mapa

when I want to access the element of a map

le digo el nombre del mapa

I tell you the name of the map.

punto

point

la llave

the key

del mapa, y puedo acceder al

from the map, and I can access the

valor

value

a la manera java

in the Java way

yo lo que tendría que haber hecho, por ejemplo

What I should have done, for example

como comúnmente lo

as commonly it does

llegamos a hacer

we managed to do

println es

println is

mapa-llava.get

map-key.get

por ejemplo, y le decimos

for example, and we tell him/her

llave1

key1

y eso, digamos

and that, let's say

es la manera en la cual

it is the way in which

nosotros lo hacemos a la manera java

We do it the Java way.

de hecho esta fue

In fact, this was.

vamos a poner aquí una pequeña

let's put a small one here

una pequeña línea

a small line

java-way

java-way

sale

sale

y esto

and this

de acá abajo

from down here

es a la manera groovy

it's in a groovy way

vamos a ver

let's see

como verán, vamos a obtener exactamente

As you will see, we are going to obtain exactly.

el mismo resultado, es decir

the same result, that is to say

en la

in the

en la manera java obtenemos valor 1

in the java way we get value 1

y en la manera groovy

and in the groovy way

exactamente obtenemos el mismo

exactly we get the same

es por eso

that's why

la otra manera de acceder

the other way to access

hay varias maneras de acceder a los elementos

There are several ways to access the elements.

de un mapa, yo podría

from a map, I could

hacerle

to do it

mandarle así

send it like this

sale, vean como estoy

Come on, see how I am.

utilizando corchetes

using brackets

para hacerlo

to do it

también es válido

it is also valid

va sin punto

It goes without a period.

ok

ok

entonces hay dos maneras de acceder

So there are two ways to access.

a elementos de un mapa con groovy

to map elements with Groovy

y hay una sola manera

and there is only one way

de acceder a esos elementos con

to access those elements with

a la manera java

in the Java way

obviamente si tú le pones una llave

obviously if you put a key in it

que no existe, no truenan

that does not exist, they do not thunder

nada, simplemente te manda un

nothing, it just sends you a

null, de hecho lo que vemos aquí

null, in fact what we see here

nos está mandando un null

he is sending us a null

por esta misma

for this same one

razón es por la cual

reason is why

yo no puedo hacer esto

I can't do this.

en un mapa, porque al momento

on a map, because at the moment

de que yo le digo punto class

that I tell him point class

lo que está intentando hacer groovy

what groovy is trying to do

es que va a buscar en este mapa

Is he going to look for it on this map?

un elemento que tenga

an element that has

como llave class, y después

as a key class, and then

ese elemento class, bueno ese elemento que

that class element, well that element that

encuentra le está pidiendo un atributo que se llama

find is asking for an attribute called

name, por lo tanto lanza el null pointer

name, therefore it throws the null pointer.

porque no hay ningún elemento que se llame

because there is no element called

class en el mapa

class on the map

para que yo pueda obtener esto, pues esto si lo tengo

For me to obtain this, well I do have this.

que hacer a la manera java, que sería

what to do the Java way, what would it be

get class

get class

y solamente

and only

digamos que es el único caso extraordinario

let's say it's the only extraordinary case

entonces bueno, los mapas

so well, the maps

en este caso

in this case

que yo acabo de crear aquí, como yo creé

that I just created here, as I created

un hash map, voy a ver exactamente

a hash map, I'm going to see exactly

que lo que estoy obteniendo es un hash map

what I am getting is a hash map

si yo quiero hacer

if I want to do

lo mismo en el mapa que me está

the same on the map that is with me

creando groovy, lo que voy a ver

creating groovy, what I am going to see

no es, en este caso

it is not, in this case

no va a ser un hash map

it is not going to be a hash map

sino va a ser un linked hash map

Otherwise, it's going to be a linked hash map.

que es la implementación que ocupa groovy

What is the implementation that Groovy uses?

para todos los mapas, si es que no le

for all the maps, if it is that you don't give it to him/her

definimos

we define

explícitamente

explicitly

el tipo de mapa, podríamos hacerlo

the type of map, we could make it

pero si tú lo haces

but if you do it

como la sintaxis

like the syntax

por default, pues te pone un linked

By default, it gives you a link.

hash map, sale

hash map, sale

muy bien, pues eso

very well, well that's that

sería prácticamente lo que

it would be practically what

haremos por hoy, espero que les haya

we will do for today, I hope it has been helpful

gustado el código fuente, se los voy a poner

I liked the source code, I'm going to share it with you.

en mi cuenta de

in my account of

github para que

GitHub for what?

para que lo

so that it

vean

look

en

in

domix, bueno aquí van a poder

domix, well here they will be able to

entrar a la cuenta de github

log into the GitHub account

y ahí van a bajarse

and there they are going to get off

el código que

the code that

vimos en este screencast para que lo

we saw in this screencast so that it

prueben ustedes en su equipo

try it on your team

repasen este video que

review this video that

estamos poniendo

we are putting

y bueno pues lo

and well, so it

aprendan un poquito acerca de estos básicos

learn a little about these basics

de groovy, entonces realmente en estos básicos

of groovy, then really in these basics

de groovy lo que vimos fue

from groovy what we saw was

que significa poner código

what does it mean to put code

así sin definición de clase en un script

so without a class definition in a script

vimos que se genera una clase

We saw that a class is generated.

internamente

internally

groovy lo hace por nosotros

groovy does it for us

vimos de una manera muy sencilla como hacer

we saw in a very simple way how to do it

ciclos de diferentes formas

cycles of different shapes

vimos las colecciones

we saw the collections

que existen en groovy

that exist in groovy

como los rangos

like the ranks

que están muy interesantes, las listas

that the lists are very interesting

y los mapas

and the maps

y pues bueno eso sería todo

And well, that would be all.

por esta ocasión

for this occasion

espero les haya gustado

I hope you liked it.

el screencast

the screencast

muchísimas gracias por su atención

thank you very much for your attention

espero sus comentarios y pues nos vemos

I look forward to your comments, and well, see you later.

en el siguiente, bye

in the following, bye

Continue listening and achieve fluency faster with podcasts and the latest language learning research.