Groovy - The Coolest Programming Language | Kenneth DeLong | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Groovy - The Coolest Programming Language

teacher avatar Kenneth DeLong, Java and Groovy Programmer

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

10 Lessons (2h 37m)
    • 1. 01 Intro

      4:47
    • 2. 02 GroovyBasics

      30:57
    • 3. 03 Strings

      8:56
    • 4. 04 XMLJson

      11:41
    • 5. 05 Regex

      12:04
    • 6. 06 Closures

      14:34
    • 7. 07 Collections

      27:47
    • 8. 08 Operators

      12:34
    • 9. 09 POGOs

      23:40
    • 10. 10 MetaObjectProtocol

      10:23
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

77

Students

--

Projects

About This Class

Groovy is a programming language created in 2003 as an enhanced version of Java. The Groovy creators took the best ideas of Python, Ruby, Smalltalk, and JavaScript and brought them to the Java platform. Groovy is not only a highly productive programming language, but it brings the fun back to Java programming!

Groovy shines as a scripting language - something you might use, for example, to analyze a spreadsheet or a set of log files from an application server. Or maybe you want to crawl your favorite website and list out all the URLs you found. Or maybe you want to write a little script that calls a web service and prints out the temperature in New Orleans every 30 minutes. Groovy can do all these things in a few lines of code.

Groovy is more powerful than just a simple scripting language, and can be and has been used to build enterprise systems. And it's completely interoperable with Java, so that your existing Java projects can start using Groovy today.

This class is aimed at someone with some experience writing Java programs. You don't need to be an object-oriented expert or have years of experience in the industry, but if you've never programmed before or never used Java before, you'll have a hard time following some sections.

Queue up the class and find out why Groovy is the coolest kid on the programming block!

Meet Your Teacher

Teacher Profile Image

Kenneth DeLong

Java and Groovy Programmer

Teacher

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. 01 Intro: Okay. Welcome to the class called Introduction to Groovy. The coolest programming language. My name's canned along and I'll be your instructor for this little class. Okay? A couple things before we actually get into some code about this class number one, this is really meant for people who have already done some programming and in particular, people who've done some a little bit of have a little at least a little bit of job experience if you're not a programmer or if you've never looked at Java before, uh, this is probably going to be a little bit too fast for you. And if you're not a programmer at all, you're gonna struggle. Understanding what I'm talking about here says for myself, I've been using groovy for about 10 years, been in software development a lot longer than that, but group has been one of my favorite languages to use for the last decade. Okay, so I wrote quickly Before we get into the technical stuff, what exactly are we talking about? Her. What is groovy? Its definition might be a dynamic programming language that runs in the jbm, and it's interoperable with Joppa. So what does that mean? Well, if you take a job of file and you change the extension from safe, I'll dot Java to file dot groovy. Generally, it's a valid, groovy file. Almost a vast majority of Java. Uh, files can be just converted to groovy simply by changing the file extension. So that's part of the source code level of interoperability. Also, you can mix. You can run mixed language projects so you can make a project that has a Java class that calls a groovy class that calls a Java class that calls a groovy class. And it works flawlessly and seamlessly, and you can compile them all together. And so that's another level of interoperability. And that's because groovy runs in the jbm it compiles to regular old job a bike code files . There's nothing special or unique about that. It's just that the groovy compiler adds a lot of magic to your source code before it generates those bite code files. The groovy project started in 2003 and it was inspired by a lot of the dynamic features of languages like python, javascript, Ruby pearl, maybe in some small talk. Currently it's a Apache foundation project, and there's to sort of aspects to groovy one is that they add a lot of really great syntactic sugar that makes common everyday programming tasks, like creating a list so much easier and so much more pleasurable than in Java. But it also has a lot of really advanced capabilities that can help you write really concise, powerful code without making without getting too cryptic, like some languages use a lot of very strange symbols, but you won't find too much of that in groovy. Okay, before we get started, there will be some projects along the way, so you'll need to have groovy installed again. Grieve runs on top of jobless. You need job A to I'm not going to walk you through in the class exactly how to install it , because it varies whether you're running on Macintosh or Windows or Linux. So you'll have to go to these websites, and I'm showing you the installation sites for job and groovy here at the time that I recorded the class and you can go and follow their instructions for your particular pat platform to get it working. This class was using Java Version eight and groovy version two dot for. And so as long as you have something that's at least that level, you shouldn't find any incompatibilities with what we're doing in the class. Now. The question might be, How do I know that I have everything working properly? So I'm on a Macintosh air and I'll show you. There's a program called I Term that starts up a shell. Now we're not going to really use the shell very much. Maybe not at all during the class. But this is a way to check that your installations working by typing groovy dash version that will come up in to tell you you can see that I'm using to doubt Ford at 13 running on JV m one NATO underscore 1 51 Again. Don't try to match those particular exact versions. Just make sure at that level or greater, and the tool that we will be using during the class all the time is called the Groovy Council. So as long as you can take groovy desk version and it comes up correctly when you type groovy console, the console should come up and there it is, And the way the groovy council works is you can top type code into the top section. You can hit a key combination to run it, and the output appears in the bottom section. So it's kind of like a really quick and dirty experimental area where you come in little groovy scripts for yourself, and this is all we'll need for the purposes of the class that we're doing. So this will be a great place to pause the class and get your set up going. Get to the point where you can get the groovy council running and then we'll be ready to start on with gravy basics. 2. 02 GroovyBasics: Okay, let's move on to the groovy basics module of the course. Groovy comes with several tools that were installed Once you've installed groupie. One of them is Groovy C, which is a compiler that works pretty much like Java Sea. One of them is the groovy runtime engine, which you use just like the Java command. Once you've downloaded Java, and then there's a couple that are unique to groovy. There's groovy S H, which is an R E P l Shell, where you can use a command line window terminal to type in groovy commands and see the results. And the other is Groovy Console, which is a graphical based, gooey editor that you can use to run snippets of groovy code and see the output in a in a graphical window and groovy councils. What will be using throughout this course to do the exercises in to explore some of the functionality and groovy, So we'll be looking at that a little bit later. So when you talk about groovy, there's one thing to know that straight up, very different from Java, there's two ways to write Groovy. One is to write classes, which is pretty much like Java, you have attributes and methods, and you have super classes and you can make subclass. Is there some special things for groovy? Classes will talk about later, but another way to write groovy that doesn't exist in Java is writing a script where you can just open a file and start writing code, and it executes from top to bottom. And those are the kind of things we can easily run in the groovy council that are easy to look at. And that's how I will be doing most of the work in this class. So groovy classes again written much like Java, they compiled a bike code. Now, everything composed by code. If you're running on the Java virtual machine, of course, which group he does. So we'll talk a little bit in just a second house. Hell, Scripture handled but groovy classes compile a job Abiko, just like Java classes, and you can easily mix Java class files and groovy class files in a single development project so you can have Ah Java class that calls the Groovy Class which thing calls a Java class. Which thing calls a groovy class and ad infinitum, and it works. If you're using maven as your build system, you can go look for the G maven plug in. Or prior to that, there was the Maven Eclipse compiler that you could use in your maven projects. Or, if using Ah, great, I'll build system. The groovy plug in itself already does this great Eliza build system that's written in groovy. So of course it handles groovy. As a first class citizen, let's look at a groovy script. So here's a Here's just some several lines of code that is written in a file called My Script that groovy, and we just start saying Into X equals five into y equals for Adam together. Print out the answer. You just start writing code like that. You don't need any imports or class definitions or main methods or anything that you need in Java and in groovy. This this file will execute so again in a script. Uh, what happens when you have a script like this? It doesn't. It's not an interpreted thing where the group where there's like a groovy interpreter that goes from top to bottom, it's actually compiled. It's fully compiled, and it's wrapped in a subclass of the groovy class called script. And so, as we know, the JBM only understands classes. It doesn't know anything about script, so it can't run a script. But what happens and normally does completely invisible to you. The programmer is that the groovy runtime will create a subclass of the class script. Take your code that you wrote, put it in the main method, more or less. This isn't exactly true. More or less. Compile it into a class file and then execute that class files main method in the jbm So from that you get standard Java execution semantics, but you don't have to do any of the work that you have to do in Java to write a little snippet of code. Let's go back to this example and look at some of the syntactic sugar that groovy adds. So first thing is that semi colons at the end of a liner optional, you can certainly put them there. Generally idiosyncratic Gurvey does not put them there. Normal groovy programs don't use semi colons unless they're ruling necessary to tell the compiler where a line is ending. But generally the end of the lot at the end of the line when there's carriage return, then the compiler knows. Yeah, that's the end of the programming line. Ah, second thing that groovy has which is kind of interesting is the key word. Death so groovy is a dynamically untie pops language. And so you can You don't need to declare the type of a variable. You can just declare it or define it which is what death. Since we're justifying a variable, why say definitely, And it equals four now at runtime. Why will point to this particular type? It's not that the instances haven't that the variables have no type. Uh, but you can think of death as kind of using like the object calling something an object. And Jarvis, you could say object. Why equals something and because object complaint to anything. Ah, all the statement surveillance. Ah, And then the last statement is Ah, print Lind pendulum will use the Portland statement A lot that just prints to standard output will talk about a little bit later and then we want to add X and y together. And then we want to print Z so we can see what the answer is. Pretty Lin is a method and Z is the argument. But notice there's no parentheses around Kremlin. Ah, well, I'm sorry around the Z that takes for the argument to Perlin, And that's because again, the groovy compiler can infer that Well, I know that Portland is a method. I know that it takes an argument. Here's the thing Z. I'm going to assume that's the argument to Perlin, and so you don't need to actually use the parentheses. I would say most groovy programmers probably do put the parentheses there because without, it can actually become a little bit harder to read when you just have a bunch of things running across the page. However, people use groovy a lot to make domain specific languages where they make ah, programming sub language that looks almost like English. And this feature is used a lot When people are making a zoo, they call them D sl's. Okay, throughout this course will have some exercises to bring home the points that we were working on, and for this one there's an exercise called syntactic sugar, so we'll do this together for the first time. Eso you know how this works, so we have to find this file called the Exercises file and let me find mine here. Uh, here we go. Sorry about that. So inside the exercises file, which is part of the skill share class that you're looking at, there are several code snippets in here that are there. Free to start off your next exercise. Now, this one says, find the one called syntactic sugar, which is just these couple lines here. Okay, so let me copy that. And it says, Put that in the gravy council. So here's the groovy council, so I'm gonna pace that in the groovy council. Now, if we go back to the actually, what are we supposed to do here? It says, Well, apply some syntactic sugar to the file. So in other words, we're just gonna do what we were doing here in the slides, but do it to our file. So first of all, let's run this piece of code. So it's very similar to what we saw in the slides. Right? And we can run this in multiple ways. So first of all, there's this little button here that says execute groovy script. You can do it. Says 10.5. You might want to look at the code and confirm that you believe that the answer should be 10.5. Another way to do it is off the script menu, which has a script run which tells you to run and also control are where command are will run the script as well. And you can see the shortcut. Uh, here on the Macintosh, its commander. Now there's other things here you might ah, under the view menu, you confined things that you'll notice like by default. The groovy council will print out all the lines of code before it prints out the actual answer, which you probably don't need. So I unchecked. I showed the script in the output, and I've also checked auto clear the output on run so that if you change your code and you run it again, the old answer gets deleted before the new output shows up. So anyway, as we look at this file and say, what kind of syntactic sugar could we apply? Well, we can take this chemical intel. Let's do that because we know semicolons or optional and groovy. All right, let's run it again here. I'm just gonna press this button and it still says 10.5 so they could still working. That's good. What else can we do? Well, we can remove the friends around the argument here, right to print them. We were just talking about that a second ago. Let's run it and see if that works still comes out to 10.5. What if we The other thing we talked about, if you remember, was the deaf keyword and let's try this. Let's turn everything into death. Let's see if you can figure out what we're talking about now. Since Deaf tells it, there doesn't give the compiler any information about X, y and Z what type they might be, what class object they might point to. So how is this gonna work? We still get some 0.5. Okay, so that's really how you use the groovy council. And that's basically the very simple introductory exercise that we use. Just to review how the groovy council works. Now there's a bonus here. Ah, on the next page, thinking about get this down. Bonus question. This what classes of the objects that the references X y and Z 0.2. In other words, to go back to the groovy council. There's three variables Her, X, y and Z. What of the class of those objects? So try to do this one by yourself. Go ahead and pause the video right here and try to figure that out for yourself by writing code anger, groovy council. And when you're ready, go ahead and restart the video and I'll help. You will go through the exercise together. Okay, I'm gonna assume that you've had a shot at the extras. I hope you were successful. One of things to remember is that these variables X, Y and Z in groovy number one something we actually didn't talk about. That which you might be worried about here is that there are no primitives and groovy like there are in Java. So there's nothing like when you say little. I meant you're actually getting a big I ended your and let's let's proved to ourselves that that's true. So remember, every object in Java has a ah, a method called get class and every class as a method called get name. Right. So why don't we try this? This is true printing it. Oops. Even get this guy print Lynn ext. Up. Get class, get one of the bad things about the groovy council is there's no coating assist like you having a good editor like until Jr Eclipse. So there's no auto complete or anything like that. You're kind of on your own, and it's a job laying imager. Well, wait a minute. Didn't we see when we started this? Let's change that back to end and it's a job laying imagers. So this is one thing to note about. Groovy. That wasn't in the slides. You don't have primitives. Even if you say int, this is actually an imager. Let's change that to death. So what do you think, then? Why is going to be why that class, the kids name. And then what about Z Z? That kit class done kid me. All right. What do you think those are gonna be? Well, why is obviously not an integer? It's got a don in it. So it's probably gonna be a floater or double, and then Z is X times Why? And hopefully that gets promoted up to the wider one. But let's run it and find out. And those air both big decimals. So Here's another thing about groovy is that when you write literal math numbers like this , like 2.1, it's not represented with a little D double or even a big D double, which for those of your computer scientists out there, you know that those air never exact representations. Big decimal is a class in Java that allows you to represent with arbitrary president precision, a decimal number. And here, in fact, we see that when you just say deaf Y equals 2.1, it actually turns it into a big decimal, and you can multiply x times y and print out the answer. And Z is also a big decimal because the big that's small time signature is another big decimal. But groovy overloads the meanings of all these operators so that you can use it as if these air primitives right? You would never guess, looking at the source code that they're not primitives. So that's just another, um, another advantage that the groupies in tax gives you. Let's get back to the slides here and we'll go through a little bit more of Ah, this syntactic sugar that's in groovy. Okay, so one thing you'll find out in groovy. Every time you write a class, you get automatic package imports. Now you know that in Java you never have to import the package java dot lang that's automatically available everywhere. Well, groovy Thought that was such a good idea. They added some more. There's java dot util is automatically package because you almost always use lists and maps and sets and things like that. Java dot net java dot io groovy dot you till, of course, and then a big desk, one big imager, as we were seeing on the previous page. And then, of course, Java that lying is imported, and there's there's a corresponding groovy dot lying, which naturally gets important as well. Okay, the groovy G. D. K. So in Java they have, ah, this idea of the job J. D. K. The Java development kit, which includes all the tools that you used to develop job in all the class libraries. So groovy has their own G d K, the groovy development kit, and what this is when people say the groovy dedicate primarily what they're referring to is that groovy through its dynamic nature, can add methods and add functionality to code that already exists, right? So this is kind of interesting. So it adds a lot of convenient message methods to classes that already exist in the J decaying classes that you use all the time. So you see the Web link there on the slide, you can go take a look at it and find your favorite Java class and see what extra methods air attitude. It's pretty cool. So, for example, to Java that lying that object, we add things like print a method called print lin in the method. Cold sleep, he says. These air instance methods which a Lisa static methods system doubt that print Lynn and thread debt sleep. So the upshot of this is that anywhere in your code, of course, you can call methods on jumbling object. And so that's why, in all the previous examples, we can just say print Lynn. And then we can just type things to be printed out, and it goes to standard out. That's because print Lin is in method that's been added to javelin object, and it's available in every single object. Therefore, in your runtime in your group here in time that allows you to Teoh to print things with a single method. Call. It's just a convenience method. Doesn't do anything radically unique or simple. But what a great idea, uh, for some other examples, and we'll go over some of these explicitly throughout the course, but just to give you, ah, slight, slight taste of what's going. Think of Java util date. Use Java Util date all the time, right, and then you have too often change it to a string or parse it date from a string. And it's kind of painful to use the job a date format of the simple date format. And then, you know, they have multiple objects running around to format and part states. So again as conveniences, they just put the format and the parts methods. They added. Those two jumpy you told date directly. So if you have date a date and you can just say four men and put in your format string and it will created a simple date for matter under the covers and output, the string that you're looking for and vice versa for parsing, uh, again nothing magical or new hair. It's just convenience, just sugar to help you make your program your life a lot simpler than it was right. And there's many, many, many more of these. There's literally hundreds and hundreds of these methods, so we're not gonna try toe to go through them here. But if if you find yourself thinking, thinking something like, What is in this class, have a method like Java that I owed up file and you say, Why can I just say file that, get text and get the text of a file? Why do I need to make a buffered reader and all these things? Well, guess what? In the gravy, G. D k. You can create a file object and then say foul dot get text And there you go. You have your text So very cool stuff like that that just makes your life so much easier as a programmer. Here's an interesting one that's worth calling out directly code. Enhance what they have for the string class. Let's say you make a string s and you have this string which looks like a girl, right https. Www dot google dot com. You can actually convert that to a to a girl by saying s dot to euro. So the method called to you, Earl is a method that's added by the G D. K to the string class. And so, if you want to call if you want to fetch the contents of your URL in groovy, you don't have to use the euro class or anything like that directly. You just make a string that represents your L U type to your L with the prince to indicate it's a method and then that returns the euro object. And the Ural object now has a property called text, which will be populated with the text that you get when you when you do an http, get on that you are so that's so so simple to write something like this. Google dot com to your oil, that text. And now you have the contents of the home page of Google as a string in your program. Very, very simple. They've handled all the exception handling for you all the resource handling is all taken care of under under the covers here and just making it easy for the programmer. If you've ever had to struggle with the Java's Earl support, you are, you're already cheering right now for something as cool. Is this Okay, One gotcha. As you go through all these wonderful shortcuts, groovy does actually change the way Great job works a little bit and that's with the equal equal operator. So if you remember and job. But when you wanna ask if two objects are equal to each other, you can do a dot equals, which calls the dot equals method on that class. Or you can do equal equal, which remember that compares the identity of the object like art. Do they have the same location and memory? Basically, is it the same object and groovy? They say that kind of comparison is almost never useful, right, whereas comparing by equals, especially if you think of comparing two strings, is always useful, right? So they've overridden the meaning of equal equal to work in something that is a little more , uh, the common case. And as they see here on the slide, if if the objects that it's calling our implement the interface comparable means they have a method called compared to it will call compared to on the objects otherwise is going to use dot equals, so in groovy equal equal Generally looks just works just like dot equals If you do want to compare identity and urine groovy and say it now I can't do equals equals how am I gonna do this? You can use dot is so you can see a dot is be And if those are actually the same object, which job would be a equal equal be that will return True if you say a dot is be And then there's this idea of groovy truth which you're also going to really love. So, you know, if you if you write an if statement, for example, you say if something that statement has to be a bully, evaluate toe a boolean, right. Uh, so groovy has this way of of coursing statements to be bully ins to become true or false in a much broader sense than Java does. So, for example, if you haven't variable, that's an object reference. Let's say you just say deaf X ray. So now excesses of reference to an object and you try to use that as the as the predicate for an if statement. So they if you said if facts, how would that job But that would just fail. So that's not a Boolean statement. That's, Ah, object reference, but in in groovy, it will convert it and say, if the object references no, then it evaluates to false. If it's not know than evaluates to true, you could also use a collection. If the collection is no or if the collection is empty, it's false. If it's not empty than it's true, you could use a string. If the string is null or empty, it's false. If it's not, it's true, and you can use a number. This one's kind of an interesting one. If the number like if you say int X equals zero, then X will evaluate to false in a boolean expression. But if you say into X equals one, then it will be evaluated. True. So zeros value to false numbers of I to true. And for those of you who have used other languages like Python or Java script, you'll be thinking, Oh yeah, this is really, really, really helpful. Shortcut in program. So, for example, here you say we created reference. String s now it's not pointing at anything. It's an empty reference. It's basically null, and then you say if s problem. It's not true. Well, if S s here is going to evaluate to false because we haven't initialized the string variable to anything. It's It's essentially no. And so the problem same will not execute. But then we say s equals Hi there as a string and the single quotes and groovy can denote a string. We'll get to that later. And now you say if s problem now, it's really true. Well, that now asset values to true because there is a string that s points at and so the if statement will evaluate to true and it'll print now it's really true. Okay, so for exercises now there's actually two of them you can work on. One is called Groovy Truth and one is called syntactic sugar to So do just what we did before. Go to your exercises dot txt file find the groovy truth exercise copied into you. Clear your groovy council. Copy that into there and then, you know, work on that exercise and then for do the same thing for syntactic sugar. And right now you can just pause the video. And once you're done, you can restart the video and then I'll be doing the exercises here for you with you. So you can see if you struggled with anything. If you just curious, you know about the exercise. I can help you out with it. Okay, so let's try these exercises. So the groovy truth exercise. Let's get all of this a copy. And then we'll go to group A council, take all of this to lead all that nonsense and then put this here. Okay, So what do we got here? Let's we can pull this down a little bit. I'm sure we don't need that much room. We have into equal zero string B list. C equals bracket bracket. It says here that means empty list will talk more about what it is later. But this is literal syntax for a list. OK? And this is print results, ABC and then prints, um, equal signs. And then it says a science and values to a B and C here and print it again. And then what's the then? Calls print results again. What's print results doing? It's taking a B and C that we have appear as arguments and saying If a equals something, then print is true else print is false. If b then print and B is true else. Print these false and that foresees. So let's run it and see what happens here. Okay, so a is false. B is false. CS false. And of course, we haven't done anything. So the second time prince the same thing. And what do we got here? Well, a is an end that's equal to zero. Remember, we said zero numbers are false. String is to be That didn't point B is a string that doesn't point to anything and see is a list that doesn't contain anything. So let's turn these guys to truth. So for the for the imager, we just set the value to anything that's non zero, right? Let's check if that works. Okay, so now you can see down here. A is now true. All right. And the same thing for B. We just need to point B at any kind of stream books of the world. And for C, it's an empty collection. So we need to add something to the collection, right? And it says the instructions say just to add an item with c dot Add. So we can add, and I don't know what's at a why not. We can add whatever we want to that collection, uh, is member A is an integer job of laying into during you can add injures two collections so went out. We do this and now all three of them are true. All right, So you can see where normally you would have to say, if a equal, equal zero, Then do this else do that. Or if B equals no or the other one that we know about. What if we put an empty string in here right when I will be his false? So in order to do the same test, you have to say, if be equal, equal no, or be that size greater than zero, something like that. Write or recall zero to check for an empty string and then for the collection. See, you could say if see, that is empty. There isn't his empty method on javelin collection, but this is just such a nice shorthand. And it also covers the case that sees no, it will evaluate to false. Okay, so that's the groovy truth exercise. Uh, groovy truth at first to a Java program might look a little bit like pink playing fast and loose with the rules, but I guarantee you want to use it. You're gonna really like it. All right, let's start the second exercise in this section, which is syntactic sugar number two. So it's grab this code here. Oops. And we're gonna take that and copied over to the Privy Council. Okay, so the instructions say, loaded the lines of a file and print the number of lines. If the file is not empty or print, a message is if it is empty, use the groovy G d k for helpful methods on Java io file. Okay, so first we need to file to read in. Well, what I'm going to use is our exercises file that we've been copying our exercises from that we just looked at and mine just happens to be located. Whoops. Not there. It's go to terminal. It's that users can documents, exercises that txt so in darkness is exercises that txt and again single quotes can make a string and groovy. We'll review strings in a little bit. So here we go. We're getting our exercises file and we want a list of the lines in the file because we're in a count, the number of lines down below. And then we're gonna print the number of lines that we're gonna print that the file was empty, right? You see that statements there at the bottom of the code? How are we going to get the number of lines? Well, it says, look for the groovy gvk for helpful methods. So let's go over to the groovy G d. K. If you follow the link, that's in the slight. You'll get to this page here. But you can see it here. Groovy, lying that it works last g k that html and probably wanna look for some cool methods on the file class since we're dealing with files. So I scrolled down here and I find file and first thing to notice that this is java dot io data file right. These are methods that the G. D. K has added onto the file class. So, like a pending text to the file, um, going through each bite, going through each directory underneath the file member of job, a Iot file can also point to a directory and on and on and on. You can see a lot of these pretty cool things. It won't be obvious yet for you how to use some of these because it relies on some more groovy syntax that we'll talk about. But the one I'm looking for is if you page down and look for things they bring back lists. You find this one read lines. That sounds kind of cool. Actually, this one with no argument read the lines of the file into a list of strings with one item for each line. Sounds perfect. Right. So what we're gonna do here is take file, Duck. Read what? Okay, now, is the file empty? Well, what would that mean? That would mean that Ah, the list called lines would be empty. Right? Doing Just do something like this. Lines, uh, is empty. All right. And the number of lines, of course. We also know that we don't need any groovy help here because that's in Jabal. You know, the size of a collection is size, right? And now we should be ready to run this and it says 263 lines. So what do we do here? We created a file object on my exercises that txt fell and you can use any textual file that you want in your in your computer. And then we said, Read the lines, the lines of the of the text that's in this Fowler read into this list called lines, and this is a Java Util list and we actually have it. And then we just say, Well, is that list empty? You could also say size equals zero or do in many ways to find out whether it's empty and get the number of lines. And they say, if it was empty than print, the file was empty. If the number of lines is more than one, then print that number and then have the word lines to it. You could also do things like you look nice print Lynn Lines zero. So if we look at our file here, the first line of the file says syntactic sugar. And so we'd expect, since we're getting the first line. And this is again some groovy extra syntax that we'll talk about later. If you're not ready for that, let's just say get at zero. Maybe that makes it look a little more like a job you to list. I run this and it prints out the first line of file. So we've indeed read the lines into memory into a list, right? Without any readers and writers and exception, try catch blocks or anything like that. All that's handled by the redefines method. So this is just a one small example of the really cool stuff you can do with the groovy gvk to really help make your proving programming so much easier. So that's the syntactic sugar number to exercise. 3. 03 Strings: Okay, welcome to the next unit in our groovy class, and this one will be talking about groovy strings. So strings in Java are pretty plain and bare, bare bones. But in groovy, they've added a lot of extra functionality, which you're gonna love. So let's take a look at this. So remember, in Java, there's one way to make a string, and that's to use double quotes to de limited set of characters, right? If you're talking about making a literal string that is in groovy, there's three different ways to make strings. So one way is with single quotes like that. First example. This is a string using a single quote. Those air just normal Java lang string objects. Nothing to see here, folks. Let's move on. You can also use double quotes now, by using double quotes, you get an object that looks and acts like a string, but it's actually under the covers. The classes G string, which is, of course, groovy string, and this is used for interpretation out. We'll explain that on the next slide, 1/3 way of making a string is to use forward slashes to delimit the string that also creates a Java Lang string object. So you might ask yourself, Why would I want to make a slash e string like I am slash e there. That's kind of a silly thing. Well, the great thing about using the Ford slashes in the slash e strings is that backslash escaping is turned off. So when Java strings of backslash is normally an escape character in a slash e string backsplashes, that's the normal character. Well, you might ask yourself, Why does that matter? Well, if you've ever tried to write a regular expression in Java, you'll know right away why this is important. Regular expressions make heavy use of backslash characters, and the fact that they are escape characters in Java means they have to be doubled up or sometimes quadrupled up in Java. And it's really very painful. Eso we'll take a look at all these things in the upcoming couple slides here. So here's the basic uses of G strings, So the first variable on the first line, the variable name, is married with single quotes. So that's just a regular old traveling string. Nothing special about it. The variable greeting is defined with double quotes that makes it a g string. And the second part of that string is dollar sign name, which the dollar sign is the interpolation token, which tells groovy that Hey, this is a G string with a dollar sign in it. You need to put you need to do a substitution here. So what it's going to do is look for a variable called name and insert that value. So the first variable on the first line is the string name. Its value is Mary. So when you print the value greeting as you see, it will print Hello, Mary. The Value Mary has been substituted into the string. Now again, think about job. To do this, you need to use the plus sign, right? Hello, space plus and then the variable name. And then Java would contaminate them for you, which is fine. The real trouble comes when you have a whole bunch of, you know, Java plus a variable. Plus sorry. A string plus a variable plus more string them a variable than a string than a variable. And pretty soon you have this long line of code where you have all these plus signs as you're contaminating all these little string fragments, and it gets pretty horrible with G strings. You can just put the interpolation tokens inside the string like most programming languages , and it's very simple to look at and read. Now you can do something more extensive, more clever than just inserting the value of variable. You can actually put a little code in there. So if you look at the third variable data, it says the name dollar sign name. Okay, that's the same thing we saw above has. Then we see the dollar sign, Curly brace form and dollar sign. Curly braces can surround a code expression. Anything that evaluates to an expression and groovy can be put in there. And so in this case, we're taking the value name and we're finding its size, which is equal into the length of the string and groovy. And when you print that out, it will say the name Mary has four characters because named outsize evaluates to four so you can do a lot with groovy G strings that make it very simple to look at the code and read it and see what it's doing and much better than Java, where you have to again string little fragments together with plus signs or use something more complex, like a string builder, which is very verbose and kind of ugly to look at in the code. So I think you're gonna agree with me that that G strings are great thing in Java for slash e strings. We're not gonna go into, like, rejects in this Ah, in this, um, unit here. But let's just say that in regular expressions, if you're matching a digit, you can use the expression back slash D. That means a single digit. So in Java and on and therefore in single quote, groovy strings, you have to escape the backslash. So it's backslash backslash D, and you can see where this really starts to get hard to read when there's multiple backslash is all over the place. If you use a slash e string in groovy, the backslash is just a backslash. It doesn't need to be escaped anymore. It's just another character, and you can just right back slash D. So when you look at your rejects, you know, instruction page or your key to rejects, you can just use what they show and you don't double up all the all the back slashes, which is really great. One more thing in Java that's very, very cool. Are here docks, which are multi line strings? Okay, so here you see this string variable ass, which is equal to a triple single quote as a string delimited er and then the string stretches across multiple lines. So this is a multi line string where you don't have to use like it, says a bunch of dumb plus signs to string it all together. And so if you have something that stretches across many, many lines, let's say like a Jason packet or something or xml yuk unjust, delimit it with triple quotes and it becomes a multi line string. And that's really great. Note that you can use single quotes as characters inside this string, and it doesn't break the delimiting. It doesn't break the string because it has to be a triple quote to terminate the string. If you do triple double quotes like in the long G string that's actually address string, not just a regular string, and you can put interpolation tokens inside that multi line string. Okay, so if you've ever struggled with this and job. If you ever had to have a string that stretched out over like, 50 lines and you had to put 50 little plus signs in there, you're going to celebrate for this, cause all you need to do is go to the top, put in a triple quote, go to the bottom, put in triple quoting you've got a string. So this is really great. Okay, so that's a really short chapter, but a couple of really small things, but that really make a big difference in your program for strings. So go to your exercises file, find the string exercises, copy and paste it into your groovy council and give it a whirl. And when you're done with that, come back. I'm gonna pause the video while you do that. And then when you're done, come back and restart the video and I'll do it with you. And you can see whether you know if you have any questions or whether I did something a little different than you, we can work on it together, and that will complete this unit. Okay, let's ah, take a look at the string exercise. So let me go find my exercises. that txt. Here's the template for strings. Copy that and go over here. This is my groovy council put in here. So it says you string interpolation to create the message. My name is Harvey and I am 44 they given you two variables here. Ah, the name is Harvey and the ages 44. So the very those two pieces of data are there, and it just says print Lynn something that prints out like that. So this is easy to to do. Based on our chapter. We just need a g g string, right? My name, books. Let's move Cursor here. My name is dollar sign names I want insert the value of the name variable here. So I put dollars. I'm name is in into the quote and I am dollar sign h All right, so if I run that I see the print out there on the bottom. My name is Harvey and I am 44. All right, Now, just to contrast that with the regular single quote string. If I did, this was single quotes, and I ran it. Notice how the color even changes in the editor. Now I get this so those interpolation tokens don't mean anything inside a single quote string a regular string. They only mean something inside of groovy strings. G strings. Okay, so that's how those G strings work. I hope you think that's as cool as I think it is, cause it's really super useful, especially if you're generating, say, like, logging statements in your program. Uh, this is so wonderfully useful. All right, that wraps up this that wraps up this unit and strings next unit will dive into something new and 4. 04 XMLJson: Okay, Welcome to the next unit in our little groovy class here called Working With XML and Jason . And I promise you, this is something you're really gonna love if you have to do this in Java. So groovy support for XML and Jason is really superb. They have parses and builders, a builders and object, like the inverse of apart, sir is used to create markup for both XML and Jason. So in terms of parses, there's actually two flavors. One is a partner, one is a slopper. So there's an XML Parsa in an XML Sloper, Jason part sir Jason Slipper. They're pretty much the same. From the user's point of view, there are some subtle differences. The Par Sur will create a dom structure by parsing the entire document, whereas the slopper is a little more lazily evaluated and just uses expressions to evaluate the things that you asked for. But from the user's point of view, generally from most use cases there, you look pretty much the same. And there's also a markup builder which is used for XML and also for HTML by extension, and the Jason Builder and we'll go through some examples of how to use all these. So let's talk about Jason Sloper first, which is my favorite. Uh, First, we create a string called Jason, which is a string of Jason. And now here were using the triple quote here docks from the previous chapter on strings. Ah, this is one of the uses just we talked about in that. You know, if you want to write out a little Jason structure in your code, it looks a lot nicer like this than it does if you're to string it together on a single line or with plus signs or some other garbage like that. So this is wonderful. We see we have a Jason object with a name attribute that values Joe. And then there's a friend's attribute, which is an array of three different names to parse this using Jason Sloper. We just say new Jason Sloper. And then that object has a method called parse Tax than we passed the string into that method, and we get an object, which is just called data here, and it's typed just with death, so we don't really know the type of it. The type doesn't really matter. It does implement the map interface so you can access it like a map. We really haven't gone over groovy support for collections like maps and lists yet, but it'll make total intuitive sense to you as we go. And so then you can do things like Puntland dated that name. So what is dated that name? While it's the name key out of that map, which has the value, Joe and then it says data dot friends dot size. And, as you see in the little call out at the bottom, that Prince Joe and then three so accessing data through the Jason object is totally intuitive. It's very much just like a JavaScript notation. And, ah, if you've ever had to do this with the parsing library in Java, you see that this is much easier and a similar thing for XML. So here's XML data structure. It's a little bit different structure due to the differences between XML and Jason, but you can see there's an XML slipper. You say parts text, you can go dated. That name dated that friends that friend dot size. So the way that XML is parsed is a little bit different than than Java script, but that will print Joe and then print to cause there's only two friends in the XML cause, you know, everyone knows if you use XML, you have fewer friends. And if you use Jason But if you had to use a sack sparser and document builder and all those of their horrible classes from the XML AP eyes in Java, you'll really appreciate this. Okay, Creating markup is similarly Justus Nice. There's ah, here's an example of Markup Builder, which is used for XML and therefore also html the the If you sing Chrissy of market builders in the constructor, you need to pass in some sort of writer that it writes its values to. So generally you just pass in a string writer. If it's not too big, you could also pass in a foul writer or something like that, and you create this object B, which is the builder, and then you say, be dot data and then a curly brace, and then you say friends and a curly brace, and then a friend notes. So, as you can see when you print it out on the call out on the bottom, right each time, there's another opening of a curly brace. It's another nesting inside the XML structure, and it becomes the next name. They're like friends becomes the next level of ah, of tag in the XML structure. And when you put in key colon value pairs inside the parentheses that follow a tag name than those become attributes inside the inside the tag and then the final string they're, like, good or bad, that becomes the contents of the tag. Right? So this is very simple now something that's not shown here. And you can find plenty of examples of this online. Uh, here we've hard coded the two friends. But what if you started out with a list of I don't know, 50 friends or 100 friends and you wanted to construct a XML structure like this? You can actually put it aeration code inside the builder so you could loop over the friend , date the front, the list of friends inside the builder and build out that list of friends into XML using a loop. And ah, we don't really have the Ben with through the time to go through all the details of that Syntex. But you can look online and find a lot of examples, and that is a very, very useful thing to be able to do now. There's also a Jason Builder, which works a little bit differently. You don't need to pass in a writer, and the way it parses entreats the the actual structures is a little bit different than the XML builder. Uh, but I wouldn't worry too much about that because, in fact, you don't often use J some builder. In my experience, you can just use native, groovy maps and lists, so we haven't really gone through, um, how groovy treats literal syntax for maps and lists. But it's actually quite simple. Square brackets with the comma separated list of items makes a list. And when I say list, I mean, like, Java that you told that list. Um, maps are very similar, except the values air key, colon value, Paris. So those air like map entries and then separated by commas. So that's very similar to Jason Syntax. Jason uses curly braces for the maps and square brackets for the list, but other than that, it's almost exactly the same. And so in groovy really the easier thing to do is just use native map and lists in tax to create your data structure and then use some of the helper classes like Jason Output, which will turn a map into a string, and Jason Help. It also has a method to pretty print a string. So the string that's created by to Jason is is not pretty. And then you pretty printed, which puts all the indentation and everything for you. So this is a very natural style for using for building Jason within. Groovy. And it's probably preferred to Jason Builder, in my opinion. Okay, so that's a touch of the flavor of it. So if you have ever had to parse XML or something like that and Java, you know how painful it is in groovy what makes groovy so good at this? Let's go back to the Jason Par Sir. The fact that you can do things like data dot name and data dot friends you can type variables as death, first of all, and second ball because it's it's loosely typed, you can say, dated that name, even though the compiler doesn't know what data is, and it doesn't know that data has a name this is actually allowed by the compiler, and then it results at runtime. So in Java, because it's statically typed and strongly typed, you can't actually do things like that. Do jump through a lot more hoops to Parson. Ah, Jason String or in XML String. Okay, that's a quick tour of that. Let's do some simple exercises. Pull out the exercise called Jason and XML, and pause the video at this place. Do the exercise, and then when you're done with it, you ca Nhan pause the video and then we'll do it all together. And, ah, if there's any questions, you know, hopefully the doing it together will help you resolve that. So go ahead and pause the video. Now, do the exercise. And when you're done, started up again. Okay? Hopefully had a chance to to do your exercise. Here, let me get mine all cued up. So here's the exercise in the file called Jason and XML. Nell. Hopefully you noticed the import statement. You're gonna need those. So don't forget to copy and paste those into my gravy console. All right, let's just give it a quick run to make sure it works in okay? runs, but there's no output. Great. At least I didn't get an exception. So first there's actually two exercises here. One is used Jason support to print the employers age. And then it says here, print the age of the employer. Okay, lets un comment that, and we'll take that a little note out. And so I want to use my favorite class there, which is the Jason Slurp. So I say New Jason Slurp er and we say parse text groups passing in the string that we have here. And then what I want is the age of the employer. So I go employer that age. I just traversed that object structure. Let's run that and see if I did that right and see what comes out here at the bottom is 96 so that's pretty cool. So the first part of that was easy. Now you could parse through the employee name or the employer name. It's really just like very much like JavaScript out notation and ah, that's extremely easy to work with. Now the next one's a little more challenging, created next Imo market that looks like this. OK, and it's already there's already string writer and a market builder created for you. And it says, Create the XML and it's gonna print the writer. It's like, OK, so use my builder The outer, uh, tag name is company. So I'm gonna do this. And, you know, I could run that right now and see, I just get company. Well, that's not that interesting is not exactly what was asked for. So let's continue going on. It's got to sub tags called employees, and they have an attribute name Mr O, not just called Smithers. Oops. Gotta terminate the same. I started it in the age is 32. Name here is Mr Lips. Come on, Burns. Age 96 and I'll strive running it again. And look at the markup that was created. That's actually what we were asked to create. So again you could be looping through a pre configured list of data. Like if you had a list of ah employees and you wanted to fill out this XML document, you could easily list that we won't go through the exact Syntex for that right here. You can find that online, But I hope you, uh, agree with me that the support for Jason and XML is really one of the killer APs inside of the groovy ecosystem. In my opinion, for those of us who work with XML and Jason a lot, uh, I wouldn't think of doing it any other way. 5. 05 Regex: Okay, welcome to the next section of our class. We're going to talk about groovy Rejects. Rejects, of course, means regular expressions. And if you don't know regular expressions, this section might be a little bit confusing. But if you do, you're in for a real treat here because groovy makes using regular expressions a lot easier than Java. Maybe even fun, right? So first of all, there's three new operators that helped to unlock the fund. The tilde operator, when it's put right before string, compiles it into a Java util rejects pattern object. So we should note here that groovy doesn't have ah, parallel regular expression implementation. It just uses the implementation that's in Java in the package Java Util rejects, which is actually a pretty robust implementation. It's just not very easy to use. Uh, so groovy ads, all these extra things on top of it, the next operators the find operator, which is really useful equal Sign Tilda, and I'll show you how to use that in just a minute. And that creates an instance of a match, for instance, which is kind of the core class for the rejects system. And then there's one more operator equal equal Tilda, which is called the match operator of the full match operator. That creates a match er and also calls the method matches own. And we'll see how that works in a little while. And then, in order to deal with match Your groovy adds a lot of extra methods to it to make it well, more groovy to work with. So let's take a look. So here's basic regular expressions, right? We have this string at the top there, and then we wanna match it against this regular expression here fl dot m So what does this mean? F l m those air regular characters? The dot means match any character, so f l a m f l o m f L Z m. Anything like that would match that regular expression for rejects. We always put them inside of slash e strings with the forward slashes. And remember, that's because slash e strings turn off the back slash Is that the backslash escaping, I should say and back slashes are a big part of rejects. There's not one in our rejects here, but generally you have. Backslash is all over the place, and we don't have to double back slash everything. Right. So we take the string s, we apply the fine operator to this rejects and that produces this variable X, which is going to be a matter. So what can you do with the matter? Well, you can say X stop find and that will print True. If there's a match somewhere in that string for that regular expression, we can print ex dot size and that will tell you how many matches in this case there's two and then we can print them out by using square bracket notation, which is groovy is notation for de referencing lists and a raise. You can say x zero and x of one, and that will print the two matches, which are flam and Pflum. If at this point you print except find again, it's gonna say false because now you you've gone through all the matches in the string and you've, ah, you basically scan through the entire string and you need to reset the matter to go back to the beginning, as noted in the little note down there at the bottom. And that, of course, is regular job syntax. There's nothing that groovy did to make that happen. Okay, Other things you can do with the same syntax. So creating the matter x again just like we did before. Same string, same rejects. And in this case, we can say collect all the matches so we say x you no matter dot collect. And then in curly braces, we put it and we get this thing Z. And when we print Z, that turns out to be a list of all the matches. Now, don't get too crazy about this lineup here. This is using the collect method comes from the groovy collections AP, which we haven't talked about yet. And these curly braces air from groovy closures. Which will we haven't talked about yet but that those are the subjects of the next two chapters. So just take that sin taxes a given now. And of course, the if you print except matches it doesn't it returns false because the regular expression doesn't match the entire expression there. Now there is a concept in rejects called groups, and let's groovy provides a ruling. Nice way of working with groups. Let's take a look at it. Here's a string which is a dash one space be dash three and I want to pull out the A in the one and the B in the three. And so I created regular expression like this that uses back slash s Remember, we don't have to escape the back slashes here, even though these Air Java strings because we're using slash, e string format and the back slice ash means non white space character. Right? So there's some numb whitespace character, you know, some visible character and then a dash and then another one. It's like, OK, so that should match a dash one and be desk three. Right? So we call except find it says Yep, you got some matches we call size. It says, True. Now, when we print x zero, the first match not only prints the string a dash one, which is what matches the rejects, but then it actually outputs a list here, or an array of the zeroth element is the one that matches, and then the first subsequent elements are the groups, right? So we have two groups in the rejects expression, the first character and the second character. So what we get when we get a match from the match or we get the full match and then group one and group to and similarly for the second match as well. Okay, uh, then there's the full match operator, which is the other operator that we can use, which is equal, equal, Tilda. And basically, what that will do is try to match the full string against your rejects. And so here I've altered the rejects a little bit. Same sort of thing. Whitespace. None. White space character dash, non white space character, possibly followed by a space. And that whole group repeated one or more times. That's what that rejects actually means. And that does describe the string that we have there. And so what you get when you say s equal equal Tilda some regular expression that returns a Boolean so X is actually bullying that prince? Sure. False. Basically, it's calling the matter dot matches method. Okay, Other interesting syntax. You might find this note. This will be useful on the exercise. Here is the same sort of met the same sort of reject, same sort of string. We've been looking at the last few slides and instead of like, printing out match zero match one. It just says m dot each, which will look through all the matches and then inside the curly braces is print Linet. Okay, so again, this is ah, closure, syntax that we'll talk about in the next chapter. But just take it as a given right now you can go through imprint, and it will refer to the match that we saw on the other page. So another thing you can do is you can dispense with the rejects operators, the tilde operator, completely. In this case, use the string a dash one space, be destry dot each match. So that's a method that's added to the string class passing your rejects. And then after that, put your closure and have that operate on it where it again is the match that will be passed into the closure. So it doesn't quite make sense yet, for you will, after the next chapter, just take that again as kind of given syntax. And, uh, you can play with it in the exercise, see how it works. Okay, so now is the time to, uh, pause the video. Start your groovy council, find your exercises sheet and copy in the Red Jacks exercise into your groovy council and and go ahead and do that. Now, this exercise is a little more challenging than some of the others, so you might have to fiddle with it a bit to get it right. But once you've done once you've got it or you've given up, uh, you can start the video again and we'll do it all together. Okay, let's go do this. Let's find the rejects exercise here. We're gonna copy it out here with a copy command, and then we're gonna go to our group console and paste that guy in. Okay, so let's see what we got here. It says find all the times in this string and print the hours and minutes separately. For example, if you find 10 Colon 40 to print 10 hours comma, 42 minutes. Okay. Ah, that sounds kind of tricky. And there's a string down below, and you can see the times in it, like 8 46 9 14 5 30 Okay, so we got a match. All those guys. Um, so we think, you know, we have to find those matches in the string. So probably using the find operator uh, now, this is not really an exercise about figuring out rejects. So there's some hints here. Back slash d means numerical digit. And so here's the rejects. You could try. So let's just try that reject. So again, we need we know we need to find it. So let's try applying the find operator like we did before. I'm going to use em for match. Er or string is s. There's the fine operator. And now let's put in our rejects, which is school, and grab this one and see what happens. Okay, so now we should create a match. Er now how can we see if it matched? Well, remember, on that last slide, we just looked at a few minutes ago. Just copy that code exactly, and see what happens. We'll run it. Okay, We got three outputs here which matched the three times in that string, and we see the full match in the first element. The hours in the second element in the minutes in the third element. So we can think back to our syntax for, uh, g strings right to enhance the output here a little bit. We have all the data that we need, right? We just need to put it into a string now. So double quotes means Ah, the G string. We know that curly brace dollar sign, Curly brace makes a groovy expression. And then what we want is the second element in the array, which for zero based of raise means one, and then we want lips. Of course, we have to close the curly brace or this is not going to work properly. All right, now let's through the minutes, Okay? So, again, what I'm doing it refers to this is what we're printing before we're printing it, which were first to this entire list. Right? I want to pull out the second and third elements, which have index one and two when you're using zero base to raise and their sin texture. That is the square bracket, right? And so, uh, in the G string, you put everything in the dollar sign Curly brace as we saw, like in our second lesson or something like that. And so this should pull out those values and then interpret them into that string. So let's try it. Let's run it. And there you go. Eight hours. 46 minutes, nine hours, 14 minutes, five hours, 30 minutes, Right. And then you get some spurious output down at the bottom, which you don't need to worry about. Um, so that that exercise was a little bit more challenging sand than some of the ones we've had before, s so don't feel too bad if it was Ah, a little bit of a of a head scratcher. We haven't really talked about the list syntax or anything like that yet, So it's a little bit of, ah of reaching ahead for you, but hopefully you could pick that up from the slides in the Rejects chapter. Okay, So in the next chapter, we're gonna talk about closures, which are really wonderful and very important part of groovy, so let's get ready for that. 6. 06 Closures: Okay, welcome back. And let's talk about groovy closures. So closures are what are known in other languages at Lambda Zor blocks, Of course, in JavaScript they're called closures. Um, but in job of their called Lambda is and again, what this is is a block of code that has an identity that you can refer to pass it around like a variable in groovy. You do these with curly braces as we'll see in a minute, and every closure is actually an instance of a special class that's in the core library called groovy deadline dot closure closures can take parameters and or have returned values and part of job eight. This was an amazing capability. Groovy. That was really compelling, you know, now, as a course of as a job eight, there are lands and grooves in job as well. So another thing that you can do now without groovy okay, here's basic syntax for closure. So when the first lying you see a standard closure, no arguments, no return value, because print lin is a function that doesn't return anything and you just see that you just put them within curly braces and it makes a closure you can assign it to a variable like see, and then you can invoke the closure by calling si dot call. When you invoke the call method on the closure, it runs the code that's inside the curly braces. Ah, the parameter syntax looks very similar to java, except the parameter goes inside the curly brace not outside like it might in Java and you say parameter name and then dash greater than seim. And now that parameter is now defined inside the block of code that comes after the parameter sign. And then when you caught when you invoked the call method, you can just pass the parameter in. So this is says print Lin s s is the parameter. When we call it here, we say call high. And so this is also gonna print Lin Hai to standard out. Uh, if you have multiple parameters, you just separate them by commas like you do in Java. You can also put the types here if it's important to say, like int or double or something like that in front of the A M B and then to have a return value. It's like any other groovy method. If the last statement has a value. If it's not void, then that value but will be implicitly returned or and that that's what it's here. But Or you could put the return statement here. You could said, Return a plus B, but this makes a little adder function that you can use to add two numbers together. Okay, Now, this kind of on the first line, this kind of ah closure definition, we have a single variable. A single parameter coming in is extremely common. And in orderto, you know, relieve you from having to write, you know, s dash greater than asked ask right. And every time you write Ah, closure for this case for this special case, if you don't put an invariable ah parameter definition, the variable known as it becomes active and that refers to the single parameter. So here I just have on the second line there's a closure called C, and it's in curly braces print lynette. And then we say, si dot call and pass in the parameter, and that will print high. So it is a special variable in the groovy syntax that refers to unnamed single parameter of a closure. All right, so this is really nicely reads very nicely. Print linnet. Right? So you know what that closer does? It prints it right? Okay. Now the mixture between job ate lamb da's and closures leads to a little bit of confusion. Sometimes let's go through it. Um, here's a list L, which is again. This is ah, literal syntax for listing. Groovy. It's just a list of strings. If I write the pure jobless in tax and it's the l dot stream map to end, and then there's a lambda here, and then I sum it up toe to reduce the stream. This doesn't compile because this is not a valid, groovy closure. So Lambda as job of functions that take Lambda as need to be fed groovy closures when you're when you're writing in a groovy class. So what does that mean? Let's go toe to the next line and say here just by putting curly braces around that you turn this little block of code here into ah ah, formal groovy closure, which requires curly braces that works okay, and that would be a standard way to do it Now, of course, um, we don't need to put Forenza around ah, single parameter to a function as we learned. Like we've seen the print lind function in the previous page. We didn't put ah friends around the parameter so you could drop the Paramus here and you and you get this lion where you just they map to end. Then there's a closure, and then you dot some it. Ah, and then one more way to make it even more groovy is that Hey, this is a single value closure, right? I don't need to write ass dash angle Brower greater than sign. I can just use it and say map to end it that size and then some. So this will sum up the links of all the strings that are in the in the map right there in the last. Rather. So just be careful when you're ah used to Jarvis in tax, you have to do a little bit of change to make it work in Group E. This is one of the very few places where literal Java syntax won't compile and groovy directly where you actually have to change something. There's only a handful of places where that's true. This is one of them. Okay, Closures, exhibit capture. So these air like Java script words You know, if you familiar with closures and JavaScript I define an integer x variable X equal to five and then I make a closure on the next line which says, Ah ah, single value closure. Single parameter closure A is X plus A. The value of X is captured from the X above. So if I say si dot cole and I pass in two as the value of a it's gonna print seven because X is equal to five, All right. And the rules on capture for groovy closures are a little bit looser than they are for Java . Lamba is a lot of times with javelins. The variable you capture needs to be final or something like that, Uh, in groovy. It's usually not necessary. Okay? And then there's some special Syntex foreclosures with method calls. Let's imagine you have a method called my method, which takes an inch and a closure. Right, So you can on the first line here, you see sort of standards in tax. My method. Here's the ant comma. And then here's the closure. Ah, block of coding club in cased in, Ah, Curly braces. But there's special sin, and that's that's fine, but you generally won't see that written. That way. You'll see it written the way it is on the second line, where the non closure parameters are put into perent. In this case, there's only one Justin Integers you say my method of five and the closure actually comes after the closing. Paramus, right? So it looks a little bit different. Doesn't look like it's a parameter to this method, but it iss right, and this is a special syntax. And if you go back to the lesson on XML and Jason and you look at the things like the Jason Builder or the markup builder that we talked about in those slights, you'll see this syntax being used everywhere where there's something that looks like a Method co. Or or even like a keyword or something followed by curly braces. And it's kind of like, Well, what is that? That's a closure that's being passed into that method, right? Uh, here. Let's say there's another method that takes only a closure, and then the typical thing to do is just write another message method no curled Nope, Arends and then just to curly braces that invoke the the that that to find the closure right. That's the most common way to see it. Um, so you can also have closures that spend multiple lines. Of course, if they take more than, um, if they have more than one line of code, it might look like this. So here's my Method five. And then the closures opened up, and it kind of looks like almost like a sort of like a method definition or something, except it's an invocation of a method. But just be aware that what this means is my method takes two variables. One is our parameters. One is five and the next one is a closure. Okay, let's give the exercise to try now. One thing to say about the slides that we're looking at here is that this syntax let's go back. The syntax where you call the closure with call is not very common. You generally will not be doing that in your code, but it's a nice way just to show how closures work and how they can be invoked. Generally, the way you'll be using closures is passing them into other methods and you'll be using syntax like you see on these last couple lines in this slide. So the next chapter is going to be about collections. Collections make very heavy use of closures, and then everything will come together in a nice package. I promise you. Then that'll look really interesting. But for now, let's just have a little bit of ah of, ah, exercise with closure. So go. So at this point, you wanna pause the video? Go to your exercises, Doc, find the closures. Exercise. Copy and paste that into your groovy console. Read the instructions there. Give it a try. And when you're done Ah, go ahead and restart this video, and then we will do it together. Okay. I hope you found that exercise. Interesting. Let's go take a look. So here is my exercises, and I got my closures right here. Copy that. Mosey on over to the groovy console and okay, so convey that. Clear. My help put there, and it says Okay, So the instructions say the list class has a sort method that takes a closure to define the sort order and then also returns the sorted list. All right, So then it says All right, so we know we have a list here of the list of heroes, and we know that has a method called Sort that takes a closure. So that's obviously what we're supposed to use. And this is sort the list and print the following list of strings, right? Print them by first letter and print them by last letter. And it's like, Well, how am I gonna do that? Well, then it says, Here's a hint. If if the variable ass is a string, you could get the first letter with S of zero like, um Ray notation and the last letter with S of minus one. This is something we'll look at in the next chapter. But how cool is that, right? In fact, it's groovy. So let's try it. Let's say we're gonna print, Let's take the comments up there and we want to take our list of heroes. Oops. Oh, yes. We're gonna sort it with the closure. Now, remember, because it's ah, the sort method just takes a closure. We don't need parental. You certainly could put Forenza. You could do this right? That's perfectly fine. But no one does that. So you want to look like all the cool kids, right? So you want to do it like this, and then it returns the item to sort on, right? That defines the sort order. So what you do here is you to return the item that you're gonna sort that you want to sort on. So for the part A it says or the first part It says, sort on the first letter and then the hint says you can get the first letter with bracket zero bracket. So what's going to be passed in here is one of these strings, like Thor, Captain America, Black widow. And so again, I can I could do this and say, Okay, I want to return. In fact, let's make it really large. Really big Syntex return hero zero. And that will return the first item from Ah, the string passed in as the list is sorting itself. And let's just run that and see what happens. Okay, be for Black Widow C for Captain America H for Hulk I for our Manti. For Thor. All right, that looks right. That's alphabetical order, But in groovy Generally you wouldn't write things like this, right? Groovy programmers tend to be want to be concise, so the return is always implicit. Let's take that out. We'll run it again. Make sure it still works yet. And what do we do with single argument closures? What? We don't actually usually pass arguments. And unless you want to make a statement about this being a hero, but we know it's a list of strings, we can see it right there. So probably we just replace that parameter with the keyword it right and I can run it and it still works. Okay, Hope that makes sense now sort by the last letter and it says, Well, how do I get the last letter of a string? Do I have to go like string dot length sub string this No. In groovy. There's this really cool notation where it says you can do a string of minus one and that should sort on the last letter of the string. No matter what the length of the string is minus one means the last letter eso Let's run it and we see Captain America A Hulk K Iron Man and Thor are black Widow W so yeah, it's sorted alphabetically by the last letter. That's pretty cool. What if I want to sort by the length of the string? Well, then I could change too. It, uh, size. One thing we haven't really talked about in groovy is that one of the things they tried to normalize was in Java. You know, you have a raise, have a property called length and lists have a size method and strings have ah length method. And there's all these of, you know, size, length, blah, blah, blah, blah. They don't that's not consistent. So in groovy, everything has a size method enable attempt to calculate its own size in some manner A string when you call size will tell its length, right? So this should short sort them in order of length. Thor, Hulk, Iron Man, Black widow, Captain America that looks like in length. And just to do one more if you want to sort them in opposite order. Of course, you just put a minus here and do that. So what's going on here? The sort method is defined in Java util list, and the sort method takes a comparator right. Ah, and so what? This does here is that the, um, closure gets cast to that by groovy and says, OK, I can use his word where it takes a comparator and then it actually runs, you know, supplies that code as, ah, implementation of Comparator. Okay, I hope that's all useful and interesting to you in the next chapter will tackle collections . And now, with our knowledge of collections and, uh, closures and regular expressions and strings now will be able to do some pretty cool exercises you'll see in the next step. So So we'll look forward to seeing them. 7. 07 Collections: all right. In this chapter, we're gonna look at groovy collections, and in this chapter, especially in the exercise, we're going to bring together a lot of the concept we've learned in the last several slides or the last several chapters. Teoh really see how powerful groovy can be. Okay, so working with collections is one of groupies, really strong sweets. It really is much easier to work with collections, and it isn't Java, and it can actually be fun before Job eight, where we got the Lambda A P I and the Streams, A P I and Java. The difference is even greater if you remember working with collections in Java seven. It was pretty unpleasant. Ah, groovy Still offer some advantages over the jobless and textures implicit. Syntex for creating collections that will look at the G D. K. Adds a lot of functionality to the collection classes that will see. And there's a new type that Griffey's added that helps work these collections, which is called a range. So first of all, one of the big advantages that groovy still holds over Java even after Java eight is the literal syntax, realists and maps. So if you want to create a list. You can see that here, you just use square brackets and you put in. You make a comma separated list of items and that becomes a list. So the square brackets in Texas literal syntax for creating a list. If you want to make a map, you just use a comma separated list of key value pairs where the key in the value is separated by the colon. So it's very much like many other languages. Look like this, if you say s equals empty square brackets that creates an array list. If you put a colon in it, that will create an empty linked hash map, those of the default types you can actually change the type that is created pretty easily. Okay, let's see how you work with list. So here's my list ass at the top of the screen. It's got three strings in it. And first of all, we see I can go Portland s of zero. And that prince a the first element the list. So just a reminder, you know, Listen, job a or zero based. So the first elements always zero. Um, but what group? He adds here is the ability to work with the list as though it's like an array. You can d reference it with the square bracket syntax rather than saying something like s dot Get, um And this will actually work for many types, not just lists. You can also have this interesting syntax of S of minus one. Now, what in the world does that mean? Well, Ah, it minus one is the index that refers to the last element in the list. So for this particular list, if you said as of minus one, you would get cheap out of the list. And now we start to see ranges here. Ranges used. The two dots will look at this a little more closely later on, but a range says, you know, go from this element to that element. And so here it says, print everything in the list from Element minus 22 Element minus one. Well, the elements are numbered from the bacca's minus one minus two, minus three. And on like that. So this says select this one to this one, so it prints little sheep when you read it. Okay. Other operators that are overloaded for collection types are the minus things like plus and minus. You can say, uh, list s minus little. And if that element is found in list, it will be removed. And then X will be a list that blacks that element So you can take things out like that and for adding things to the list. One of the most common ways will see it done is with the double left angle angle bracket, which is just Aziz the ad method. So if I say s bracket bracket farm, what I get is, ah, list like it shows at the bottom with the value farm added to the end of the previous list s. So those are all really nice little syntactic shortcuts that can make your coat a lot more concise when when all taken together, okay, very similar with maps. Here's the way the standard way of defining a map is like this. We have key colon value key Colin Value key, Colin Value. So this is a map with three entries, and one of the cool things about groovy is that generally they know that keys to maps are usually going to be strings right. That's just very common in programming. And so when you write map like this, like this value A. It kind of looks like a variable. It's not quoted as a string. But when it's in the position of a map key, groovy will by default assumed that you meant that as a string so that this first line is equivalent to the second line where there were the keys are actually quoted to make them traveling strings and this perfectly legal syntax. But generally, people leave off the the quotes, the string quotes because it's understood that the keys were gonna be variables now getting things out of a map again very similar to what we saw with less. Here you condemn reference a map using angle bracket notation, but you put the key value in there instead of the instead of, ah positional value like you would for a list. The keys here need to be made into strings because there's no there's not nothing special about this position here, but the keys also appear as properties on the map. So you say m dot be. Obviously, a Java Util map does not have a property called get B, but groovy will interpret this as get the value that exists under key number Be so we'll print it was will print too, just like the first line. And you can also use the standard get methods in tax, which still exists on the map. Of course, for putting things into the map similar set of shortcuts you can say m dot d equals four and that will create the key D and assign it the value for you can say m of e equals five and that will create a key named five with the value Sorry key name the with the value of five. Or you can use the standard maps in tax of put. All these things are equivalent in how they operate on the map. Okay. Beyond those literal syntax is, there are a bunch of extra useful methods at the G. D. K adds to the collection classes. These air really groovy methods here. Uh, nowadays, in job ate, a lot of them have analog in the job. Eight ap I prior to that, of course, this was the only wayto to get this done in Java. Ah, a lot of these arguments, just like in the streaming a P I and Java, where many of the methods on the streams take a lambda and groovy. They think a closure and the idiomatic style again, is not to use parentheses just to put the curly brace right after it. So, for example, sorting a list list that sort. And then you just put in the curly braces and putting your your sort comparator. And we did this in a previous ah exercise. Okay, so we're not going to go through all the extra collection methods because there's so many of them. But let's look at them a handful of, um anyway. So there's There's a method called collect, which is a really helpful method. What collect does is it takes a closure that can transform each element, and the transformed elements are collected into a new collection, sort of like if you use the J. D K Stream Method map and followed it by a collect dot to list, then you could reproduce what the collect method does. The find all method takes a closure that has that returns a bullion and the bullion would indicate Teoh keep the element for the new collection very similar to a JD key filter, followed by a dot collect to list something like that. Each does something with each element that's very much like the J T K. For each method and sort. Just like J. D. K Sort creates a new sort of collection. So let's just look at each one of these. These were some of the these air four of the more common ones that you'll see used all over the place. And let's take a look at how they look in code. Okay, so here's the same list and let's say I want to create a new list, which is the size of each of those strings. So the first string here a has the size of one. The second string has the size of six, and I want to do that. I can take the list, ask dot collect and pass in a closure that that maps each element that transforms each element. So here I'm just calling it that size. Remember, it is the implicit variable for a single argument closure, right? So when you're using these methods on ah, on listen other collection types, they're passing in one element at a time to the closure net element can get the variable. Name it, So I'm saying it that size that gets the list of the string When I print it, it's gonna print this new list of one common six Come a five, which are the lengths of the strings here in the original list. It's very succinct, very terse. You can do this pretty easily with J. D. K H Streams, but it's a lot more, uh, typing a little bit more ceremony. Let's say I just want to make a list. I want to call down this list of the words that are short, so I want to say list, find all. And then I pass in my closure it that size less than three. So this returns a Boolean tour false. And if if the item of the list passes this test, it will be put into the new collection. Of course, the only string in the original list that is shorter than three characters is the 1st 1 A. So when you print that, you'll just get a all right. Let's suppose I just want to look through the list and do something with each element, like, you know, just in iterated er so I can just say s dot each and then print Lynn. And here I'm doing a little more fancy stuff. It dot to uppercase dot to upper case is a method that exists on Java Lang string, right? You just say it that to upper case, and it would print it out like this. Right? Each element now in the original collection goes on a separate line because we've used to print line here and print Lin will always that a line return at the end. Okay, let's support I want Let's suppose I want to sort my list on the length of the strings inside of it. Then I can do s dot sort and I can use is my comparator again it that size and it will print as it shows down below. If, uh, Google slides will stop messing up our screen, you can see that it prints them in order a sheep little because they is the shortest word and little has the most characters. Okay. And like I say, you may want to look through the g d k documents for java dot util dot collection and also list and map and see all the other extra methods that have been added. They'll work kind of like this. Um, and there it's a very, uh, the FBI is very congruent, but there's a whole bunch of things there that you can find that are useful. Okay, and then we talked about range is a little bit. We saw the the dot dot in one of the listing references. Ranges are a new type added by groovy and basically what it is. It's a sequence of ordered values, so you can write a range like this or equals three dot dot five. You put it inside of perent, and now you can, because this is also a Nitta rubble type that has multiple elements in it. You can use some of the same methods on it or dot each and Perlin it, and it will print 345 because those are the values in the range, you can ask a range. Do you contain this value and it will tell you if the value is contained within that range ? Um, you can also, uh, creative ranges of characters as below. So from a to F, you can say a doubt that effin groovy will go through the natural ordering of of those characters until you create a range out of it. So these could be really useful to the place where you really see them. The most is what we saw up above, which was as a way of the referencing a sub list of a list. So you know, if you need to take, let's go back and look at that. If you need to take a sub list in Java, it's quite a bit of comfort. Teoh put in you know, sub listen in the beginning index and last index, which is often size minus one. And so I get to call list dot size minus one again, and it turns out to be really long and ugly with groovy. You can make a range like this dot dot, so if you want the 1st 2 elements, you'd say zero dot dot one. If you want the last two elements, you say minus two dot dot minus one. It's all very compact syntax and very quick and easy to write. Okay, the exercise. Now this collections exercise is a lot more challenging than the exercises we've had before , and it draws together a lot of the concepts that we've seen in the last four or five chapters all together on one big exercise, one exercise that is quite realistic, something you would actually do in your day job. And, ah, I picked this exercise so you can see how simple groovy can make things that you need to do at work and just whipped through them in basically a single line of code. Okay, so again, at this point, you'll want to turn off the video or pause the video. Don't turn off. Just pause it. Go get the collections exercise from your exercise text. And again, it's much longer than the previous ones. We had to be prepared. Paste it into your groovy council and see if you can follow the instructions there and completely exercise. And when you're done, you can go ahead and restart the video, and then I'll do it with you together. Okay, let's work on this collection. Exercise together. So here's the collections exercise from my class document. I'm going to go and copy and paste that from here. So copy. Take that over to my groovy council and pasted him. Okay, let's see what's going on? So, uh, it says, Here's a list of errors from an application log. The message is contained and you're a bug tracking number. For example, are STI 12 87 or A N 2 13 Using rejects, collections, closures and anything else, you need to write a script to count how many the errors there are of each type and print. The list says something like this. Okay? And they give you a couple hints. There's account by method on the list class, so hopefully you've had a chance to go. Look at that. And here's a useful regular expression. Okay, so let's take a look. We've got this string s and let's see what this is. See what? This is it The beginning. A triple quote at the beginning. In the triple quote at the end, this is one big, long string that is, has multiple carriage returns in it. It's a multi line string here, doc, right? And that's what we've been given Someone's copied and paste this out of an application log or something like that and plopped it into our script here. So, uh, and then what we have on each line, It looks like there's one error on each line inside that string, and there's some time stamp that we don't actually care about for this exercise. There's some text that we don't care about them. Toward the end is the Jura bug number. Sometimes it's the last thing. Sometimes it's in perent. Um, sometimes not. Sometimes it's a three letter abbreviation. Sometimes it's too. Sometimes it's three numbers. Sometimes it's four. So it sounds like it's pretty painful, right? And so this is totally like something you might have to do it work. So let's start with this. Say, we'll just start with just printing s okay. That doesn't help us very much. Notice that the first line is like a line of of a header. And I'd really like to get rid of that because there's nothing in there that's interesting . Um, currently, remember, s is one big old string, right, and we'd like to split it into lines so we can go through and treat each line individually because there seems to be one bug report on each line. Right? So let's do this. First split hoops split one backslash them, which is a new nude line. Okay. And now, if I run this, it's a much harder to read. But when you split, this is just like the Java Util string or juggling string split. It turns it into an array of strings. And let's see, we've seen this now. Maybe it'll print nicer if we print it like this just to take a look. Okay. Ah, one of the things you find about the groovy council is it likes to print step after it's done said to stop that. This is put a Perlin blank there and it's still doing that, Not quite sure why. Okay, so we see that now we're able to split this into individual strings, and now we know that we don't want the 1st 1 So let's use our little range operator. I remember going to go from one to the last one. So why am I doing this? I want to take the collection that was created by this split operator, and I want to say I don't want the first element. I want Second Element Member zero base to raise so that zero is the 1st 11 is the 2nd 1 all the way to the end, right? So when I read this. Now I see that the first line no longer prints out. Okay, great. So now for each line, I want to find this. Want to extract this bug number? Right? So I've got this line here, and I just want to get this. And it looks like that might be useful for regular expressions, right? And so, uh, remember at the top, they gave us a hint. They said this could be a useful regular expression. Let's take that. And that. The regular expression I gave too, because this isn't really a class about regular expressions. And what I want to do is looked through this list of strings that I have now apply a regular expression to each one and then put those results back into another collection. Right? So that is the collect operator and what I'm going to do. Is it equal till if you remember from our regular expression class, put the rail expression in there. Okay, so let's stop there and see what not what am I doing? So I'm saying collect, which says loop over every element in this collection, which are all these strings excluding that first header and then apply this regular expression to what is his regular expression. Say it says, look for some capital letters. So this square bracket a disease says Look for capital letters to or two or three of them in a row, right? That's what this regular expression means again, if you don't. If you really want to look into this, go to this job. A Dock Java Util rejects pattern. That's where all of this is documented. And then there's a dash and were followed by back slash D three or four of those will back slash D stands for a digit 0123456 29 right, which is what we have here, and there's either three or four of those. So if we look through our list of strings here, we see that we always have two or three letters, and we always have three or four numbers s. Oh, this is a pretty restrictive rejects toe only Look for exactly that pattern separated by a dash. All right, let's run it and see what we get. Well, we get for we get for each Ah element in this collection now is now a job you Toll rejects match. Er Okay. Well, that's not really that interesting. Remember what we saw with matters was that you can get the match out of them by, uh, treating it like an array. Right? So we can say it once again, collecting to get a new collection match er the first match. And they use just it of zero. So it would be the match. Urbi hopes there needs to be dot Here it will be. The mattress of this expression transformed the string into a match er by playing a rejects against it. And now this one is going to take the input to this is going to be the match er coming in. And what we want to do here is d reference the first match. And by looking through this, we kind of see that it only prints the bug number once it's not like it's printed three or four times in each line. So only care about the first match. The only match which will be zero. Let's see if that did anything good. Okay, here we are. We see that each line now has been transformed to the string that matches and we got theocracy 12 87 0 LS 40 fours. Where is that? A n? That's an outlier. That's a little bit nasty. There is an to 13. Okay, great. So now we have a list of all the bug numbers. That's nice. Um, and now we want to count. Each of them will remember they give us another hint. They said there is a count by method. So let's see what that's gonna do. Instead of printing each one, let's do account by All right. And we got a no pointer because we didn't tell it what to come by. Well, in this case, all we're gonna do is count the individual occurrences of the strings, right. We're not, like, trying to count by. They're the ones that are greater than zero. Anything like that about some other predicated. We just want account by the actual string, run it again. And now we get something like that, okay. And the reason why we're getting the extra characters that I didn't understand before, it's because I left the print line here, which I forgot about, um so in a split, I want to count those. And now I want to look through them, and I could do something like to make a nicer display than what I have when you look so count by has given us a map here, look at what we have. We have in square brackets with a comma separated list of key colon value. Right. And the groovy Methodist counted for us. And so when I loop over a map, you can you can generate with each and say, get a an entry. If you're familiar with Java maps, you know that they can have Ah, they have their composed of entries which have a key in a value. But in groovy, you can just say key value directly. I just want over, over, right over, loop over those. I'm gonna say print when and I'm going to say, uh, feller key colon dollar value. So what I'm doing here is taking each each key value pair in the map and I'm making a string here. Why put key and key value and I do a print line, so they should each appear on one on one per line. Okay. And right now they're sorted from most frequent to least frequent, which is what we wanted but that's kind of an accident. It appears that, uh, we didn't do anything to sort them. So you might before you print them. You might want to do something like this, sort by, uh, that value. Okay, So what's going on here? So again, remember, after we apply the kelp by operator, we get a map and I'm going to sort that map. And now I'm just using the single argument value for the for the closure. And so that's gonna be the entry Java Util map entry object is going to come in here, and it has a property called Get Value it. So we say value there, and I'm gonna sort by value now what's gonna happen here? It's going the wrong way because value when you sort by value values and injure. Or maybe it's a long but it's gonna sort from It's gonna sort in ascending order. So actually want sort in descending order. I want the most prevalent one first, right, making my bug report for the week. And now, by changing that sort order to minus, we print them from the most prevalent to the least prevalence. So we no longer relying on just coincidence that they came out in the right order, their actually being sorted in that order. Okay. And you can confirm this by doing something. Let's take, uh, one of the 12 87th and just converted to an IOS 3 64 So let's do that right here. This is cheating. But I, uh, s dash 364 That'll give two of those. Let's let's make it an A in 213 That'll being better and dash two on three and we run that . And we see that now that one moves up into the third position because it has two instead of one where it was tied for last. Okay, so this is our expression. Let's take a look at it. Is this little expression here? Online 93. Does the entire thing force right? Take this big string, split it into individual lines, trim off the first line which was a header that we didn't like. Match each line individually against this regular expression. Pulled the match out of each match. Er convert to a map that counts the number of occurrences in that list. Sort that map inversely by the value which is the count of each error message and then go ahead and print them out on the screen. So if you've ever done a lot of, ah, working in Olynyk shell like bash were used, grab and count and sort and things like that and cut to parse through logs, you can see that this has a very similar kind of feel. And if you tried to do something like this, it's a room of this just to get out of the way. I tried to do something like this in job, but this would take many, many lines of code. But if you're just analyzing a log file like if you just pulled this off your server or out of a log collectors somewhere, you just want to get account. Uh, you really are not that interested in, uh, writing a big job, a program for it. And, you know, doing an in bash might turn out to be even way harder than this. Groovy is kind of a nice medium where it's a lot more powerful than bash. You have all the operators of the J, D. K and G K at your command, but it's way less formality than Java. And you see, you can just kind of string together the entire thing as a single line, and you can save this and, you know, use it again some other time. Okay, Hope that exercise really helped you to pull together all the concepts. I know I probably did a lot faster than you did, Um, because there were a lot of pieces to this and a lot of thinking how it how it might happen . And this is not the only way to solve this problem. Of course, there are multiple, multiple ways you could go about trying to do this. And ah, this is just one way that that I picked here for the for this demonstration. But I hope this kind of convinces you that Ah ah, Powerful scripting language like groovy could be really, really useful for day to day work as a software engineer. 8. 08 Operators: Okay, let's move on to our next section, which is about groovy operators. So first of all, in this section, I'd like to show you that gravy. Add some pretty cool new operators that you're going to really wish you had in Java. There's the no safe D reference, the Elvis operator and the spread operator as some examples. So let's go through these one at a time, okay? No safety reference. What does this mean? Well, suppose you have some variable X that you've defined, and if you're afraid that X might be no, then you have to do this nerdy thing here where you say, if X equals no then, well, return know otherwise, return X not size. And that's a really awkward Syntex that you see all over the place in Java. So groovy gives this knoll safety reference where you say return X question mark dot size. And that's a shortcut operator, which is the same thing as the the nerdy way up above. Write a check sex for no effects is no. It stops there and it returns. No, but if it's not, it calls the size method on X. So look at that last line person don't get named that size. You're not sure if the ref the variable person is null or not. And if you have a non no person, you're not sure whether the name is no or not. If you have to do that with nested, if person equal Equal Knoll, then if person that get name equal equal. No, you do things like that in Java. It's very awkward, but with the no safety reference. It's so simple and easy to read. So this is a wonderful operator that Ah, maybe one day the gods will smile on us and we'll get this operator in Java as well. Okay, the Elvis operator. So here's another thing that you have to do a lot. I want to assign value to the variable. Why? And I want to give it The value acts if X is assigned to effects, is not No, I want to assign it the value of X. Otherwise, there's a default value that I have. So this designing, assigning defaults is very, very common, right? And so look at the second line where you say why equals X question mark equal default and what that says is Why is gonna equal X unless exes no and effects is no. Then there's a default value there. So assigning defaults when variables or no is really common, and you're gonna love this notation for doing it. It's called the Elvis operator, cause if you kind of turn it on its side, it looks like Elvis's, you know, hair cut and his eyes there. Okay, Another operator that groovy ads is called the spread operator. So here's a collection of strings at the top X. It's a list of strings, but the strings have spaces at the beginning and or the end, and you'd like to trim them all. Well, it's actually not that hard and groovy. It's only partially nerdy to do it with the with the collections. AP I because we have this nifty method called collect, and we have this nifty thing called closures. And so you could say as it shows, extract, collect it dot trim and that would loop through the collection, trim each value and then put it in a new collection. Why, that's actually not to un cool. But the even cooler way to do it is to use the spread operator where you say? X split dot trim and that's how it's pronounced. The stars pronounced splats and split that says applied this method trim to every element in the collection, right? So it's very similar to that. Ah, uh, line above. And if you wanted to. Instead, let's say you had a collection of I don't know people and instead you wanted a collection of their names. You could say people split dot get name, and it would create a new collection with just their names. So the spread operator is, ah, is could be very useful as well. So those are some of the built in operators. That groove you have groovy has that they present to you. But there's more that you can do because in groovy operators air methods, right? So when you haven't expression like a plus B in Java, that's sort of, ah, primitive of the language. But in groovy, that's just a method call. It's a shortcut for a method call on the class of the variable A. So you say a dot plus B is really what you're saying when you say a plus B on the plus sign is just kind of a convenience because it's a lot easier to read than a dot plus B. But what this means is you can override or customize the plus method. All right, so let's see how this works. First of all, let's take a look at some of these. So you have plus in minus. And you also have divide and multiply, of course. Um, the plus plus and minus minus operators. Correspondent. Next. In previous, we've seen the square bracket notation for de referencing lists and maps. Right, and this is how it works Underneath the covers. The square bracket notation is a shortcut for calling the get at method. So a list a Java Util listing groovy has an extra method added called Get at which, As you know, in a job, a list. There's a method called Get where You pass in an index, so get at just defers to get, uh, the same thing for a map. When you have a map and you have square brackets it calls get at on the map and that just calls get on the map class so that that's pretty cool. Uh, another interesting one is for the switch statement. We'll call this method called is case. And so what this means in practice. You know how in Java you're limited to doing switch statements on Denham's and imagers and you know some other primitive types. But in groovy, you can make a switch statement. Work on any any type that you want by implementing the is case method, all right, and there's some other things, like the A in be asking where A. Is a member of, uh, some other variable B the the so called spaceship operator, which is less than equals greater than that is a shortcut for the method compared to. And as we know, that method returns. Ah zero. If they're equal but a minus one or a plus one, depending which one is greater. There's the as keyword, which calls the method as type on AIDS class, and that allows you to do like no safe casting and things like that or very clever casting . If you want to cast one type to another, you can use the as operator, and that's that's barely scratching the surface. There's about 20 or 30 of these more. I think that that you can look up and customize, So let's take a look. Look at one in particular. We're gonna look at this one here, the next operator, which goes with plus plus. So let's say I have a class called person, which has, ah, two attributes on integer age and a string name. And then I implement a method called Next on this class which returns a person. All right, so that's how these operator methods work. They return an instance of themselves. Generally you've returned this, but that's not always the case. And in this place, what we wanted this define is that when someone calls plus plus on a person, we're gonna increment the age. So here we're calling age Plus plus, which is kind of ironic that we're using plus plus on the age to implement, plus plus on the person. But that's OK. And then down below we have this idea. Here's a person we given a name and an age okay, using ah groovy constructor that will see in the next chapter. And then we say the person the reference for person is P. That's the P variable and we say p plus Plus what does that do? Plus Plus is the shortcut for invoking the next method. And what that's going to do is increment the age of the current person object and then return a reference to that object. So then, when you say print Lynn p dot age, it's not gonna be 41 instead of 40 because you've plus plus the person which increments the age all right, and you conduce those sorts of ah, you can add operators like this to any class that you want in groovy by as we go back a slight by implementing the proper method right with the proper signature. So this is a very powerful thing, especially if you're building domain specific languages or other kind of ah enhanced syntax . You can leverage this to make things look really interesting. As we'll see in the exercise coming up, we'll give one little example. Okay, so it's time for the exercise. Let's let's implement an operator. And so here you like you would stop the tape. Stop the video that is, go to the exercises sheet, get the operators exercise, paste it into Privy Council and follow the exact instructions and linger. Done. You can restart this, uh, video, and we'll do it all together. Okay, Let's see how it whips. Let's see how this Ah exercise goes. So we'll go here and will say, Here is the operators exercise. Let's grab this a copy. Go to my groovy council here. Well paced and okay, let's read the instructions. We want instances of our person class to get married simply by writing people in plus P two . So we have. P. One is a reference to one person. P two is reference to another when they get married. We just want to write p one plus p two. That's how we want to write our code. Right? So alter the person class to make the code below work. Okay, well, that implies that it doesn't work, so let's try it. Missing method exception. Okay, let's see what we got. We have a person method that has any I'm sorry. Person class that has ah, name. Okay. And then we have a marriage class which has two different persons spouse, one spouse to, and it's got a little too string method there. So the code we see down below is person P one equals Harry Person p two equals sally and we want to marry them by saying people in plus P two and that should create a marriage object . Okay, let's take a look at this. So we want to implement and and it extra shows. Here we have this plus method. We need Teoh implement, and we're going to say public hopes now. In this case, the examples we saw before putting a plus method on the person would return a person. But here, as we see in our code, were expected to get a marriage back. So let's try making this a marriage. Plus, when we adding a person to another person, all right, that's who we need to do here, and what we have is a marriage takes to, uh, arguments in the constructor spouse one and spells too. So for the first spouse, I'm going to say the current person and for the second spouse, I'm going to say the other person that was passed him okay, so again, I'm using this Syntex for the constructor that shows that uses the maps in text. We actually haven't really talked about that yet. That will be in the next chapter. But we did see an example of it in the in the previous chapter. So let's run this and says, When Harry met Sally, they got married. So it actually worked. We returned to marriage. Object there. So look at the code that you end up writing. Person P one person p two marriage equals p one plus p to its You can create very expressive. Ah, I suppose this could be called a very simple version of the domain specific language. Right? So you can create a very expressive domain, specific languages and groovy by judiciously over operate overriding these operators, like Plus and the reference operator get property operators and things like that, and you can make code really look a lot like English if you want to. All right. I hope you enjoyed that lesson. Uh, will move on to the next lesson in the class after this 9. 09 POGOs: okay, In this lesson, we're gonna talk about plain old groovy objects. Or, as they're known affectionately, Poggio Pogo's So groovy adds some really nice enhancements. Two classes, of course, being ah Java jbm Language It, of course, understands classes as a za native concept, and there are some really cool things that are that are offered, like auto properties and different types of constructors and some things like that. And just like people talk about Poe, Joe's in job odds. Plain old Java objects we talk about Pogo's in Groovy is plain old, groovy objects. These are sub classes of traveling object, although the groovy G. D. K adds a ton of methods to objects that are available everywhere, and they also have their own special super type groovy object that you can look up and see what's on it. Let's take a look at what we're talking about. Here's a class called person, and it's got two attributes age and name, a ninja registering and just like in a Java class, when you do to fly in an attributes, you could make it public or private, of course, and those have the same meaning and groovy as they do in Java. But what happens if you leave off the visibility identifier? So in Java it means package level visible right. But in groovy, it means something different. It means make it a property. So what does that mean? Well, with this class definition here, class, person into age, string, name. And that's it. Just those three lines of code. Ah, and you create a person. The compiler generates a get age and set age getter and setter for age and a get name and set name getter and setter for the name property. And you can say P dots at hp dot get name. And even though those don't appear in the code, those air still available to you to call, which is pretty nice, right? And you can actually shortcut that even further you can do. You can write code like p dot name and P dot age, and it kind of looks like you're accessing those attributes directly, but you're not. That actually goes through the getter in the center. The compiler will generate the code that will actually make it used. The getter and setter. When you write this sort of property deep reference notation but auto properties like this on Pogo's or super useful. All right, now what if you one a customize the getter or the center a little bit? So here's another cloud. Here's the same class person with a two properties, age and name. But I want to put some instrumentation and to get in the getter for name, right? So I can actually just override the getter for name, Public string. Get name, and I can put in there whatever I want. Make it do whatever I want. And the groovy compiler will see that, and it will not try to generate a new getter for name. It will not override it. It will still generate the center because name is still a property. Ah, so the jet set the standard setter will still be generated. But because you've supplied your own getter, it won't try to override that or or reproduce it in any way. So you have full control over what you're getters and centers look like, but you're not obligated to write any code if you don't want to. Okay. And of course, if you make a nah tribute, private or public, it works just like Java There's no auto generation of getters and centers, it's only for properties, which is default visibility. Okay, now it's kind of interesting. It's actually gets complicated and starts to lead into the next chapter. How does groovy resolve properties like when you have a person object, you say person that name, What's it actually doing? Well, it actually goes through multiple levels, and one of one of the first things it does is call the get property method with the key name on your person class if you've implemented that method so you can actually implement to get property method on your on any of your classes and intercept these property calls to do something crazy, if you'd like to failing that and if that that method doesn't exist, then it will call the get name it'll call the Getter. And then after that, if the if the getter doesn't exist, it will try calling the get method on the person class and pass in the key name. So there's multiple levels of of customization available here, and we'll look at this a little more deeply in the next chapter on the groovy Metal Object protocol, as it's called now, Of course, if you don't have a get method or get property method, but you do have a getter, the compiler will optimize away all of this complexity at compile time if it can. Okay, there's even more ways to deal with properties and groovy. So here's that. Are same person class again. I'm creating a person filling in the two attributes and will look at that style of constructor in just a moment. There's a method that's on every groovy object, or I'm sorry, a property called properties So you can say Pete Out Properties that returns a map of the properties and all their values. So the keys would be name an age, and the values will be clown and 40. So then you could say, Pete out Properties of name. That's a standard de referencing a map using the square brackets. And we know from last chapter that just calls the get at method, right, cause it's, ah, one of these operator shortcuts. You can do p dot properties dot name, which is basically the same thing is calling. Get on a map object and you can even just Deve reference the p ah reference itself the reference of the person itself with square brackets, which would call get at which groovy objects also implement get at. And then it would look for the property named name. So there's multiple ways of doing this. And it's a very complicated sequence of, ah, priorities as to which method can be called. Now this kind of syntax actually leads you to to something that's really quite interesting and groovy. And let's say, Here's my person again. Same person object and I want to get the name O. R. I want to get a property out of the person object, but I have the property name not as a hard coded method call, but it's being passed in somehow. Maybe maybe the users typing in age at the command line, right? And at the or in a gooey or something. Say, I want to see the age of the person they're typing a. G. So you have this string here, which has the name P name, which has the Value age and when I'm trying do is find the age of this person, so you need to use some kind of dynamic reflection capabilities and in groovy. This is so simple. You just say p dot and you can make a G string out of the method name, so double quotes Remember G strings or double quotes. The dollar sign is the escape value, right? And then P name is the name of this variable. So the string p name or more specifically, the string G string dollar sign P name evaluates to age and you can actually write this code and it will print 40 when you run. This could. So this is very interesting. If you have properties that you're trying to pull out of an object and you don't know which property until runtime and somehow you have the property name and you want to get it. You can use this syntax to do that. The other thing that's really fascinating about this in taxes, for example, in Java and Java. A method name with the with the hyphen in it, or minus sign. Whatever you wanna call it is not valid, right? The compiler will refuse to compile that. But here you could construct I I should say a property name that not really a method name. But here you could make a property name called my prop with the dash in the center and you can access it in groovy like hard coating that I believe is also invalid. But you can access that property using this syntax, creating the string my prop, which is a valid string and then using the G string notation to pull the value out of the objects. So this could be really useful. If you're like parsing Jason or something and you have jet the Jason has a key that is an invalid Java. Specify where that say it starts with the number or something like that. How are you going to get that key? You can't write that code, but you can use this notation to circumvent that restriction. So this is actually really cool. Okay, The constructors we've been bumping up against the constructors, the last chapter or some. And let's take a look at what this really is. So, by default, a groovy object gets this constructor, which takes a map, and what you see here is you see key value pairs separated by colon, so it looks like a map. Now, in this case, you don't need to put the square brackets around the map It's a special case in Groovy the Compiler. It's a little bit of extra syntactic sugar that says in a constructor, If you're passing in what looks like key value pairs, yeah, we get it. That's a map. And they're going to map the keys in the map that you put in the constructor call to the properties of the object. So we know that our person class has the properties, name and age, and we can actually just pass them in like this in any order. They don't need to be in this order, right, so name could come first. Age could come first. Doesn't matter because they're named parameters, basically. But what this is under the covers. This gets turned into a map and then passed in the constructor. Um, other more interesting ways of ah, of creating objects are to use an array. So in this case, we say array of 32 comma Joe, and we just assign that to a person P and the groovy runtime will automatically convert that into a person. Now it's careful to note that in this case, the order of the arguments actually matters because there's no way to tell which value is supposed to be assigned to which property. So you have to put them in the array in the same order that they're defined in the class. That's a little bit of a restriction here. You don't have that restriction with the map based constructor, and if you want to be a little more clear about it, you can use the as keyword and you can say 32 Joe as person. And that will use the Remember from the operator chapter that uses the as type method and will turn this array into a person object with those values set for its properties. Okay, here's something that's actually a lot more practical, I think, and that is using closures or maps of closures to masquerade as objects. Now, this is really interesting. Syntex, look at this. I have person p equals a map. Okay, so you see square brackets here as person, so I'm gonna build a map, and then I'm going to cast it to a person. All right, so the as person is what turns it into a person object lets me a sign it toe this variable p but what's inside the mat? What's inside the map are key value pairs where the values or closures and the keys are method names in the class, right? So what this says is that this is going to create a person where the get name method has been overridden by this closure and the get age method has been overridden by this closure rain. So every time a call, the person p and us A ah p dot get name, it always returns. Barney, even if I say p dot set name to Fred, when I go pee dot get name, it's gonna return Barney because it's hard coded to disclosure. And that's what the get named method actually invokes that particular closure. And so this turns out to be super useful when you're writing unit tests. So let's take the typical case here. You have a service object that you're testing, and your service object has a repository or data access object that it talks to, which is generally connected to a database, and you're trying to write a unit test. You don't want a database. You just want to test the service, saved a mock out or stub out these repositories, and this could be really painful and boring. But in this case you can say service stop person Repo assuming the name of the variables person repo and you signed that equal to closure and you cast it using the as keyword as person repository. So it turns it into a personal repository and assigns it to this value in the repo. And now you can put anything inside this closure that you like here it says, Return new person. Now, in this case, we didn't use a nap of method names to closer. We just use a single closure. And that's a shorthand notation of saying all the methods on person repository are gonna be stubbed out by this return. New person closure. So any time you say person that repo dot find person repo dot save person repo dot block, it's gonna invoke this return new person, which may or may not be what you want, depending on your test, so you can then go to the more powerful since actually of different methods doing different things. But in my experience, this is absolutely the quickest, most robust and most powerful way to mock out dependencies for unit tests, and I think when I write, unit tests are almost exclusively and groovy, almost always so I can use this kind of ah, syntax. Okay, some other things that are really cool and groovy methods are default. I'm default values. So here I have ah, method called adder and I say into adder, and I haven't and then to be as parameters. So there's several things going on. As there noted in the calls here, um, if you don't provide visibility by default, it's public because the creators of Groovy said, look, most of time, wing right methods their public. So if you don't, you don't need to write public if you don't want to. Um, the second thing you have there is Look at this word. Syntex here into B equals 10. That's a default value range of default parameter values. So let's see how that works. Looking at the body here, it's a plus. B. What the heck while there's an implicit return state, remember, remember, from the very first chapter, or maybe second chapter, we said you don't need return statements in your methods if you don't want to. Their implied right, So that's cool. So here we say print Lynn Adder of five and two and we expect that to print seven. But what now we can do this print Lynn Adder of three. So we've only assigned a single parameter, which is the 1st 1 We didn't assign anything to the second parameter, but the default value is 10. So that will print 13. Right, So this is another very useful shortcut. All right, get more cool ways to use groovy classes. So groovy. The groovy compiler makes visible the a S t the abstract abstract syntax tree that it creates when it parses your code and it opens up in a p I for you to put transformations on that to change it. So what in the world does that mean? That means code can be generated and modified at compilation time with a very simple addition to the code, these generally are triggered by annotations. And so you can basically create an annotation that that causes code to be generated. Throw that annotation in your class and all this code will magically appear. Let's see what? Let's see what we mean. Here's four really cool annotations that come with groovy straight out of the box you want to write anything, let's see how they work. So the 1st 1 that's kind of interesting is the to string annotation. So here's my person class again that we've been looking at and you slap a two string method on it, create a person, and then you say, print limpy. What's that gonna print? Well, now what this does at compile time, it adds a two string method to the person class that prints out by default. The standard behavior is to print out the value of the attributes in the order that they're defined, right? So it prints out the class name and then in forensic value of the attributes, which is no pretty useful thing. If you're just like doing some debugging, the two string annotation has a lot of attributes that you can use to customize it. For example, you can make include and exclude lists of property. So, you know, if I don't want to do this property or that property or only care about this property, I can do that in the annotation itself. I can tell it to include the names of the properties, so if we go back instead of just saying Person 40 clown. It would say person age equals 40. Name equals clown. So if you're object, has a lot of attributes. You may want to see the names. Anger. Two strings. Um, you can have some you can say ignore the fields and only include the properties. You can say Ignore anything that's no, you can say include properties from the super class and on and on. There's a bunch of things you can do with the two string annotation. Very, very flexible. Another one that's very cool is the immutable operator. So if you're done any multi threaded programming, you know that immutable objects air super useful. And if you've read the book by Joshua Block, you'll find you know that creating a really, truly immutable object is kind of a pain. There's, like 14 things you need to dio, right, and this immutable annotation does them all right. So, for example, it makes the class final. It removes all the centres. All the properties must be immutable. They must be clone herbal. It makes defensive copying of any mutable fields like Java Util date or anything like that , and on and on and on, like it basically implements the list of transformations you need to do that Joshua Bach Block put out on making safe, immutable objects in Java, and all you need to do is put at immutable above your class name very, very useful. Another one that's really useful is canonical. So a lot of times you want to have an equals and a hash code and the two strings that in a constructor that's just based on the fields that you've created, like a economical job of being like like our person class. It has age. It has name and I want haven't equals that compares. These are the age and the name the same in a hash code that does the same in a two string that prints those out. This is very common, and so you can just put at Economical as an annotation on top of your class, and you'll get all this stuff generated for free. Another super interesting one is that is this one called Compiled Static. Now groovy is a dynamic language, as we're as we've seen and as we're really getting into here and you may have been thinking earlier in the chapter, it's like, Jeez, I call person dot name and it goes through, like, 84 different methods, right? It looks that the get method and the get at method and to get property method and all this crazy stuff, like, how slow is that going to be? Right. And it can be slow if you're in a tight loop and, ah, you know, you have lots of ah, these dynamic features being used. And so if you really are not using any of the dynamic features of groovy, which you can do a lot of things without it, you can use this annotation, compile static on a class or a method, and that turns off all the dynamic typing, resolves all types at at compile time and basically turns on like Java, static typing and by passes, all of the what they call the metal object protocol and groovy. And the reason it does that. Number one. It makes it way more type safe and number two. It makes it faster, so you don't have any of the dynamic checking or anything like that that you do in standard groovy. Another, I should say another byproduct of make of adding compile static. It makes it easier for your I d to track down what it is you're trying to do because it knows that it can apply static typing rules now to this method or this class. And it helps it to do re factoring and things like that. Okay, so that was the discussion about Pogo's plain old, groovy objects. So now is the time to pause the video. Go find the exercise for Pogo's in your exercise file pasted into your groovy council. And once you've done it, you can come back and start up the video again and we'll do it together. Okay, let's take a look at how to do that that exercise. So let's go find the pogo's exercise. And here we have it, uh, pogo subgroups. Let's copy that. We'll go over here to our groovy console and, uh, do that and let's see what we got. It says. Create an instance of MISC this classes to find here using the map constructor, then looped through all the properties and print them out. Okay, well, the map constructor. We've seen this multiple times now, so this shouldn't be hopefully a big deal to you. It's just called the object in we say new misc and then we passing a map here. Now you can put them in inter Gorder you want, so you can say Oops, sorry. Count is four length is 4.2 that let's do something different. 7.1, Um, name his Joe. And what's less happy? Of course we're happy. All right. And so then so that's using the map, Constructor, Let's get some space Is here to make it look nicer. Okay, now, again, you could put the square brackets in here, but no one ever does. Right on that says look through all the properties and print them out. Are you going to do that? Well, if you remember back in the slides, we talked about being able to get a map of the properties of an object by doing this thing end up properties. Okay, great. Now I want to look through those and create some kind of formatted print statement Right now, I could just say I could run here and it would print out this map using the groovy to string method that's on map. But let's let's go along with the spirit of the exercise and say if I want a loop through any kind of collection maps or lists, the method is each and then pass in a closure. Now for maps, you could just use it. Or you could define a variable here If you'd looked through a map, it's gonna pass in in trees where entries have a key value. But there's an overloaded method of each for map where you pass in the key value already unwrapped like this. So you get a two argument closure where the first argument is the key, and the second argument is the value. So I'm just gonna say, print Lynn. I use a G string, of course, and I'm going to say the key is okay and the value his color V Okay. And then when I run this, I see it planning. Now look at this. It's using the It's also printing out the property class, which maybe I didn't want that right, so they could say if G equals class came. Oops, just exit the closure at that point. And now I've only got the ones that I have defined their and if I don't like this ugly thing at the bottom, I could just have one more print. Lynn, this is just a groovy council thing. Clean up the output. A little bit printed, empty line. Okay. Hope that made sense to you in the next chapter. We're gonna look dive a little more deeply into the groovy metal object protocol. 10. 10 MetaObjectProtocol: Okay, Welcome to the next interesting topic. Which is the groovy metal object protocol. Let's talk about what this means. So groupies, a dynamic language. And we haven't seen too much of the really hardcore dynamic stuff. But you can do some pretty wild stuff with groovy. Look at this. Code simple here in the block. This is actually groovy code, right? So this is what you would call a domain specific language. It kind of looks like structured English, right? Doesn't look like sort. You wouldn't recognize that its source code at all, But that can actually be executed. Ble groovy could. So how in the world would you do that? Well, you use this facility inside a group he called the metal object protocol. So by default, groovy doesn't just execute methods directly like Java does. Calls are routed through another layer, which is called the Metal Object Protocol. This is a really rich and complex subject, and if you've never done dynamic programming before it, it's probably going to seem pretty confusing. So we'll just take a tour and take a look at some of the main features, so you kind of get a feeling for it. so I've already seen the method or alluded to it This get property method that you can implement on a class. So here I have a class called Pretender and I've implemented a method called Get Property, which takes Ah, string name, which would be in the name of the property. But no matter what, it returns 23. So now I can create an instance of Pretender P and I can say p dot anything and it's gonna return 23 no matter what. Now there is no such method or property on the class called anything. But this code actually runs, right? So that's kind of interesting. You can do the same thing with methods. There is a method called method missing, which is a special method name. If you implement that on your class and you call a method that doesn't exist, it will route the call to this method, the message method, missing call, and it will pass in the name of the method and the arguments that were passed in. So here I'm just going to print out the method that was called and then I'm gonna return the value okay. As the return value so pretender p and I say p dot nothing of five. Now, once again, there's no such method called Nothing on this Class. But this code runs and it will print called Nothing with five and, you know, passing in the array of parameters and then it will return. Okay, and that'll get printed cause there's a print Lynn there on that line. All right, so you can fake out properties. You can fake out methods with the get property and the method missing. There's also a property missing, ah, one that you can add so that you can call it when there's no such property available. And so here's a pretender peeing you say p dot non existent and it prints called non existent, just like Thea. Implementation of property missing looks like. Okay, so you can fake methods, but you can actually also add methods to objects so you can add method dynamically. So here's a pretender p one. Now every client, every object in groovy, of course, has a class just like in Java. But they also have a meta class, which is where the metal object protocol lives and you can say, like people end up meta class dot yell and assign that to a closure here. That's basically what you're doing is adding a new method to your medical ass. So why would you want to do that? Well, now you can call p one dot yell, and it's gonna execute disclosure when you call that method right, and now I can create a new pretender, P two and I can also call Yell. The method is added to the middle class, which is shared by all instances of the class pretender, right, And this is called monkey patching. And that's why they call it monkey patching, because it's really dangerous, right? Adding new methods to the middle class mix them shelf globally, which maybe is not so horrible. But you can also modify methods and that will show up globally. And that could really screw up some code elsewhere in your code base. So groovy includes another facility called Categories, which lets you scope this down a little bit. So here's the class I'm making called explosive category, and there's a single method. Their public static void blow up takes a string. OK, so the way these categories work because there's the first argument is string. This is a new method called Blow Up, which is going to be available on string classes. So what's it gonna do? It's going to print. Dollar s says kaboom and what His dollar s It's the actual instance that you're calling blow up on. So it's a little bit confusing. Let's look at the example down below. So there's a string called Captain and the value is Morpheus, right? And now I use this special keyword called use and I say used the explosive category, and I pass in the type reference to to the category object that I'm using. And now after that, I have a scope with curly braces. And within that scope, all strings will now have this method called blow up and you can call it. And so here we see the captain string even those to find outside the use category. The captain object now has this blow up method attached to it. And when you call it, it prints out Morpheus says, kaboom because more fuses the value of the string that you're actually calling it on. Okay, so you can write these categories and into multiple methods to add two different types. And then you can have a black bloc of code where you say Use this category and you can deeply alter the way that the types in the in the program behave by adding, subtracting, modifying all these methods using categories. And it's very it's way safer than monkey patching because the scope of these extra methods are limited to the scope of the use statement. Okay, and we talked about the meta class a little bit. The meta class allows you to do reflection and introspection a lot more simply than you do in Java. So the medic class, as methods like, has property and responds to, and you can pass in property names or method names, and it will just return billions. It's like OK, yes, you have it. You don't have to look through a list of names and try to hunt for the name that you're looking for anything like that, and also for manipulating objects. You can invoke a method through the, uh, meta class, and you can get insect properties through the meta class as well by calling invoke method and get property set property. So that's a lot easier than using Java Reflection Teoh to do this kind of thing. And also, you know, we've seen we've gone through many other ways that you can do the same sort of things and getting and setting properties in particular. So that's a quick tour of the metal object protocol. There's actually no exercise for this chapter because it's so complex and so mind bending that any simple exercises not really gonna help that much. If you want to use the Met object protocol, you're gonna need to sit down for several hours and go through all of these different ways of invoking it. And in depending on the use case you're trying to implement, then you can decide what's the best way to do it. But remember that that's Ah, little strip of what didn't look like code it all in. The first slide of the chapter actually is code and executes. By using all these methods method missing, property missing and monkey patching and categories and things like that, you can make code like that execute herbal, which is quite interesting if you're interested in building a domain specific language. All right, so that brings us to the end of our course. This was an introduction to the groovy programming language, which I think you'll probably agree with me now that this is probably the coolest programming language, right? Um, here's a quick wrap up just to sum it all up for you. This is a Java based, dynamic language. It's it's practically a super set of Java with dynamic features added to it, inspired by python, PERL, javascript, maybe a little bit of, Ah, small talk and ruby as well in there. And there are some test that it's brilliant EDT. And remember the exercise we did. We had that log file taken from a real life server with bug codes in from a Jura bug tracking system and in one line of code, were able to zip through that and find out how many bugs there were of each type and print them out in descending order of come of Ah, you know, Occurrence. That's pretty, pretty sweet, right? And also for unit testing. We didn't really go into this deeply, but remember the slide. We talked about how you can step out or mock out objects using closures and groovy and make them do what you want. If you get good at that. That makes your unit testing so easy that, plus the, um, the literal syntax for maps and lists and also the map based constructors. So, you know, if you have an object that has, like, 40 properties and you're just testing one of them, you can create that object and just use the map constructor to set that one property. You don't need to set the others. You don't need 50 new constructors for your unit tests or and you don't need to supply 50 unrelated values for parameters that you're not testing right. Makes working with collections of real pleasure with job eight. This is not such a big step above job a anymore. It's still easier than Java, and there's a lot less ceremony installed with concerned with it. But even so, it's still a little bit nicer. Uh, and if you want to do things like DSL Zangana dive deepen in the metal object protocol, you can really go down the rabbit hole here and make some really amazing and cool stuff. The website now is revealing that organ at the current moment. That's where the Apache Foundation hosts this project. You can go there to learn more. There's also probably the best book is called Groovy in Action that's written by the team that that works on groovy and amended, groovy. So that's worth looking into if you want to go further and ah, it's when the thanks for sticking through the course.