Groovy Simple Guide

Source: Internet
Author: User
Tags closure iterable object object

Frankly speaking, I have never been so optimistic about this scripting language. The reason may be that they are not so eager for new technology now. But I have found that this is not a good idea. So I finally decided to use groovy to see what the wind was doing to make it look good.
Of course, I do not know the language very well, so there may be a bias in my discourse. Also hope Haihan. Environment Construction

The most popular package management building tool in the back-end of Java now is maven. Of course, the environment of this article will also be built on Maven. In fact, the process of building is very simple, only to introduce the appropriate jar package dependencies.

        <!--https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all-->
        <dependency>
            < groupid>org.codehaus.groovy</groupid>
            <artifactId>groovy-all</artifactId>
            < Version>2.4.5</version>
        </dependency>

In principle, only the above-mentioned dependencies need to be introduced. or Hello World,

It seems that this is a charm to avoid the open. Examples of the basics of getting started with programs are to take this example. In fact, I think this example already has a certain symbol. Aha, gossip doesn't say much. Get to the point.
To create a new groovy source file in your project, enter the following code.

Package Io.swagger.script
/**
 * Test
 * @author Fulei.yang */
class Test {public
    static void Main (string[] args) {
        println (' Hello World ')
    }

}

Well, let's explore the information from this most basic example, and we can get some of the following information:

1, groovy can also like Java has a strict class structure, of course, you only write a line of println in the groovy file is also fully executable, the reason why this is because it can facilitate the Java and groovy calls between each other.
2. Groovy has streamlined some basic Java operations, but this is only a small part of it.

Okay, let's take a look at the results of the run. You know, it's very important.

the difference from Java

In fact, groovy is also based on the scripting language of the JVM, which can be found in a variety of search engines are quite rich answers, the Ford here is not to repeat. Let's look at some of the more basic differences. string

In groovy, single quotes are wrapped in strings, however, double quotes are not simple strings, but gstring. This gstring is not easy to do. For example, it can be used as follows.

Package Io.swagger.script
/**
 *  Test
 * @author Fulei.yang */
class Test {public
    static void Main (string[] args) {
        def a=
        println ("A===========${a}")
    }

The result of this code is not hard to guess, here is to show that groovy will take the value of the variable in the $[} in gstring. This is a very important feature because there is no need to use the + number connection string again. Of course, you may be concerned about the performance and efficiency, to tell the truth, I am also very worried, but I am writing this article, the question will be left to discuss later. A todo here, huh? Basic data Types

For Java, there are eight basic types of data, many people have been talking about this is the product of the last era. Because this is obviously the last process-oriented language left. How can great object-oriented Java possibly tarnish object-oriented sacred vows because of eight basic types. In fact, such a discussion is very common in foreign forums. So, what does groovy do with basic data types? In fact, groovy treats it as an object, which is a very interesting thing. Groovy, as a scripting language, completes Java's transition to real-object object-oriented.
We can take a look at a simple example.

Class Test {public
    static void Main (string[] args) {
        def a=
        println ("A===========${a}")
        println ( A.bytevalue ())
    }
}

Here you can see a simple example where groovy is a loosely supported script and a strict class syntax definition. Love and hate. the collection in groovy

We know that one of the most common classes in Java is a variety of containers, what map, List, set, and so on. It's very java. These collections are actually a manifestation of a variety of data structures in Java source, which is the reason to emphasize the Java code implementation. Because only you know a variety of implementations, you can select the most appropriate container for your current problem context.
OK, now let's look at what's in groovy.
Groovy's containers are divided into three main types. Lists, map, ranges.
But the difference is that groovy provides more powerful functionality for the operations of these containers. Where is the specific strength?

public static void Main (string[] args) {
        //Set definition
        def lists=[1,3,4,5,6,7]
        //Direct take subscript access
        println (lists[1))
        //map defines
        def map=[
                ' 1 ': 1,
                ' 2 ': 2
        ]
        //map access
        println (Map.get (' 1 '))
        println (map.) 1 ")
        //range definition
        def range=1..10
        println (Range.get (1))
    }

From the above we can see that when we want to initialize a collection or map is so elegant, so that we have to jump up happily, no longer need to first new map, and then put it all into the inside. Well, the range here may not be very understandable, but it's actually a range, and groovy makes it incredibly easy for you to access it.
Having said this, let's look at how to traverse lists. You will feel very sour here.

        Set definition
        def lists=[1,3,4,5,6,7]
        Lists.each {println (IT)}

What is this, oh my God, this is simply too simple, OK, of course, the more concise the code the higher the cost of understanding, this is the truth. So, what happened here, anyway, let's take a look at the results first.

Sure enough, the effect just, however, we need to consider is, why can this be written. The following chapters reveal the answers. Groovy Closures

I think that if you have more or less contact with a scripting language that actually touches this concept, which is a very important concept, then, in fact, closures are not a new concept, but they are often used in functional languages, which allow you to execute a code block that is arbitrarily specified. Even if you say this block of code as a function of the actual argument into the total no problem, well, so powerful function, ah fu some can't wait.
Closures are not a new concept, but they are often used in functional languages, which allow you to execute a code block that is arbitrarily specified. In layman's parlance, a closure is a block of statements enclosed in curly braces, like any other code block, in order to pass parameters to the closure, the closure has a set of optional parameter lists, "->" to indicate the end of the list. Let's try to define an example of your own closure:

    def a={int A,int b-> return a+b}
    println (A.call (1,2))

It's not really difficult to guess what's going on here. But understanding the intrinsic mechanism is more complex, and it is fundamentally helpful for the examples that have just traversed lists.
Let's go back to the Lists.each (). Always keep in mind that the source code contains the largest amount of information.

/**
     * Iterates through a List, passing each item to the given closure.
     *
     @param self the    List over which we iterate
     * @param closure The closure applied on each element found
     * @return the self List
     * @since 2.4.0
    /public static <T> list<t> each (list<t> self, @Clos Ureparams (FirstParam.FirstGenericType.class) Closure Closure) {return
        (list<t>) each ((iterable<t>) Self, closure);
    }

We can see this place actually passing in a simple closure and the list itself. That is, every time an element is traversed, the closure is executed once. If everyone is interested, we will continue to go in.

/** * Iterates through a iterable, passing each item to the given closure. 
     * * @param self the iterable over which we iterate * @param closure the closure in each element applied * @return The Self iterable * * public static <T> iterable<t> each (iterable<t> self, @Clos
        Ureparams (FirstParam.FirstGenericType.class) Closure Closure) {each (Self.iterator (), Closure);
    return self;
     }///** * Iterates through an iterator, passing per item to the given closure. 
     * * @param self the iterator over which we iterate * @param closure the closure in each element applied * @return The Self iterator * @since 2.4.0/public static <T> iterator<t> each (iterator& Lt
            T> Self, @ClosureParams (FirstParam.FirstGenericType.class) Closure Closure) {while (Self.hasnext ()) {
            Object arg = Self.next ();
        Closure.call (ARG); } rEturn self; }

The source of the problem is here, in fact, there is still a way to iterate through the iterator, but, these operations are placed in the closure of the code block, we use it does not need to care related things good, no longer Baidu.
In fact, the highly abstract here is because we give the details of the collection traversal to the so-called closure, rather than our hands-on operation, we can do so, we will continue to manage the file resources to the closure. We can do it just by using it without paying attention to the release of the resource. In fact, groovy does the same to simplify IO operations. Let's look at an example of IO operation.

        def file=new file ("D://test.txt")
        file.eachline {println (IT)}

Well, that's an explanation for this ubiquitous it. Closures can actually have parameters or not, where it is implied parameters, it is important that lists traversal and file read-by-line reading to use. Groovy Database Operations

In comparison to Java, groovy operates a database with a much simpler API. Put the sample code first.

Get connection
def conn = Sql.newinstance (Url:envMap.url, User:envMap.username, Password:envMap.password, DriverClassName:envMap.driver)
//Execute Query and traverse
def sql= ' select * from Test '
conn.eachrow (sql) {
               println ( it.tostring)
            }

OK, it is so simple, I think the most important thing here is closure, so we can understand the concept of closure, the benefits of infinite ah. Summary

At the end of the line, let's summarize the main idea of this article, which mainly describes the differences in groovy with Java and Groovy's enhancements to some basic Java operations, and of course the most important and difficult to understand is closures. You know, it's very important to be the soul of groovy. Of course, groovy is so good, hurry up and use it. You can call groovy in your project directly.
Finally, thanks to all of you can read this long article, I wish you all the technology continues to progress. Ford in this bese.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.