"1" Groovy language Learning: Groovy language Introduction and basic syntax

Source: Internet
Author: User
Tags class definition closure constructor modifier grails

Groovy is a JVM-based Agile development language that combines many of the powerful features of Python, Ruby, and Smalltalk. first, what is groovy?

In short, Groovy is the next generation of the Java language, and, like Java, it runs in the JVM. As another language running in the JVM, groovy syntax is similar to the Java language syntax. At the same time, Groovy abandons Java's cumbersome grammar. With the same statement, groovy can reduce your keystrokes to the maximum extent possible. Second, groovy syntax introduction 1, no type of Java

As a dynamic language, all variables in groovy are objects (similar to the. NET Framework, all objects inherit from Java.lang.Object), and groovy does not require coercion of type declarations when declaring a variable. Just ask for the keyword def before the variable name (starting with groovy JSR 1, in previous versions, even def is not required).

def var = ' Hello '
println (Var)
println var
println (var.class)

def var2 = "Hello2"
println (VAR2)
println var2
println (var2.class)

The printing results are as follows:

Hello
Hello
class java.lang.String
Hello2
Hello2
class java.lang.String

Process Finished with exit code 0

You can see that the program finally outputs the actual type of Var: java.lang.String
As an exception, the declaration of method parameters and loop variables does not require def. 2. No public required

In fact, the default modifier in groovy is public, so the public modifier doesn't have to be written at all, which is not the same as Java. 3. No statement terminator required

There is no statement terminator in groovy, but you can use it as a statement terminator in order to maintain consistency with Java. After each of the preceding lines, the code ends and the program runs normally (in order to accept the stubborn habits of Java programmers). 4. String Connector

Like Java, if you need to write a string in multiple lines, you can use the + sign to concatenate strings. The code can write this:

def var = "Hello" +
"World" +
", Beijing"

println (Var)

def var2 = "" "Hello
World
, Shanghai" ""
println (VAR2)

Description: There is no need to connect between three "numbers" (although the format characters in the string are preserved, including carriage return and tab).

The printing results are as follows:

helloworld,beijing
Hello
world
, Shanghai
5. All Objects

It sounds like "all sentient beings are equal", in fact groovy does not care about what type of object it is, and the type of a variable can be changed at any time in the run, depending on the need. If you assign it a Boolean, it will automatically convert the type to a Boolean value, regardless of its original type, after it accepts a Boolean value. Look at the following code:

def var = "Hello" +
"World" +
", groovy!"
println var;
println Var.class;
var = 1001
println Var.class

Printing results:

Hello world,groovy!
Class java.lang.String
class Java.lang.Integer

var is a variable in a program, and the type is changing. At first, it is assigned a string, and its type is string, which is then assigned an integer, and it is converted to an integer. 6. Circulation

Delete the entire source file content and replace it with the following code:

def var = "Hello" +
"World" +
", groovy!"

def repeat (Var) {for
    (i = 0; i < 5; i++) {
        println (var)
    }
}

repeat (Var)

println ("--------- ----")

def REPEAT2 (Var) {for
    (i in 0..5) {
        println (var)
    }
}

Repeat2 (Var)

Printing results:

Hello world,groovy!
Hello world,groovy!
Hello world,groovy!
Hello world,groovy!
Hello world,groovy!
-------------
Hello world,groovy!
Hello world,groovy!
Hello world,groovy!
Hello world,groovy!
Hello world,groovy!

Note that there is no def in front of the loop variable i. Of course there is no common int in Java, but if you have to add int it's not a mistake, because groovy starts with the Java Classic for loop notation starting with GROOVY1.1BETA2 (excluding 1.1BETA2).
In addition, the for statement above can also be written as: for (I in 0..5)
The result is the same. 7. String and Gstring

In addition to the standard java.lang.String (surround with the ' number '), groovy also supports gstring string types (enclosed in "numbers"). Change the statement in the For loop above to:

def repeat (Var) {for
    (i in 0..5) {
      //  println (Var)
       println ("$var: $i")
    }
}

repeat (VAR2)

Run it and you'll understand what gstring is.

One more example:

def STR1 = "Programming language"
def str2 = "Groovy"

println "$str 1: $str 2"
println ' $str 1: $str 2 '

The results show:

Programming language: Groovy
$str 1: $str 2
8. Scope

This is the same as the "sub-realms" in Pascal. In the previous for loop introduction we have used the for (I in 0..5) such usage, where 0: 5 is a range.

The range is a series of values. For example, "0..4" indicates that it contains integers 0, 1, 2, 3, 4. Groovy also supports exclusion ranges, and "0..<4" represents 0, 1, 2, 3. You can also create a range of characters: "A.. E "corresponds to A, B, C, D, E. "A: 9, default parameter value

You can specify a default parameter value for a method. We modify the definition of the Repeat method:

def repeat (var, time = 3) {for
    (i = 0;i < time;i++) {
      //  println (Var)
       println ("$var: $i")
    }
}< C7/>repeat (VAR2)

As you can see, the repeat method adds a parameter repeat (and gives a default value of 3) to specify the number of loops. When we do not specify the 2nd parameter to call the repeat method, the repeat parameter takes the default value of 3. 10. Collection Collection

Groovy supports the two most common collections of Java: Java.util.Collection and Java.util.Map. The previously mentioned range is actually one of the set (Java.util.List).

Collection collection:

1. Define a set
def collect = ["A", "B", "C"]

//2, add element to the set
Collect.add (1);
Collect << "Come on";
Collect[collect.size ()] = 100.0

//3, SET index
println collect[collect.size ()-1]
println collect
println Collect.size ()

///4, negative index
println collect[-1]      //index its bottom 1th element
println collect[-2]      //index its bottom 2nd element

///5, set operation:
collect=collect+5        //add element in the collection 5
println collect[collect.size ()-1]

collect= Collect-' a '         //Subtract element A (1th) from the set
println collect[0]          //Now the 1th element becomes B

//6, adds another collection to the collection, or deletes a collection:
COLLECT=COLLECT-COLLECT[0..4]   //Remove the first 5 elements of the set
println collect[0]   //Now only one element in the collection, that is, the last element
of the original println Collect[-1]  //You can also use a negative index to prove that the last element is the first element

The print results are not displayed. 11. Map Collection

Map is a collection of "key-value" pairs, in groovy, the key is not necessarily a string, it can be any object (in fact, the map in groovy is Java.util.LinkedHashMap).

1. Define a map:
def map = [' name ': ' John ', ' age ': +, ' sex ': ' Boy ']
println map

//2, add:
map = map+[' weight ' : +/       /Add John's weight
map.put (' length ', 1.27)      //Add John's height
map.father= ' Keller '//         add John's father
println map

//3, two ways to retrieve values:
println map[' father ']//       via key as subscript index
println map.length          // Index by Key as a member name

Print as follows:

[Name:john, Age:14, Sex:boy]
[Name:john, Age:14, Sex:boy, weight:25, length:1.27, Father:keller]
Keller
1.27
12. Closure Package (Closure)

Closures are blocks of code that are enclosed in {symbols, which can be run or invoked alone, or they can be named. Similar to the concept of an ' anonymous class ' or an inline function.
The most common application in closures is to iterate over the collection, and the following defines 3 closures that iterate over a map:

def map = [' name ': ' John ', ' age ': +, ' sex ': ' Boy ']
map.each (
        {key,value->     //Key,value two parameters to accept the key for each element /value
    println "$key: $value"})

map.each{println it}     //it is a keyword that represents each element of the map collection
Map.each ({println It.getkey () + "--" +it.getvalue ()})

Print as follows:

Name:john
age:14
sex:boy
name=john
age=14
sex=boy
name-->john
age-->14
Sex-->boy

Other than that:

In addition to being used for iterations, closures can also be defined individually, such as defining a required package:

def say={word->
    println "Hi, $word!"
}

Call:
say (' Groovy ')
say.call (' groovy&grails ')   //call is a must-package method

Print as follows:

hi,groovy!
hi,groovy&grails!

It seems that closures are similar to methods that require defining parameters and statements to be executed, which can also be called by name. However, the closure object (not surprisingly, the closure is also an object) can be passed as a parameter (for example, the preceding closure is passed as a parameter to the map's each method). In Java, it's not easy to do this (perhaps a function pointer in C + +, but don't forget that there are no pointers in Java). Second, closures can also be unnamed (and, of course, at the expense of defining closures only once), and methods are not. 13. Class

Like the groovy class and the Java class, you can define a groovy class with the syntax of a standard Java bean. But as another language, we can use a more groovy way to define and use classes, so the benefit is that you can write less than half of the JavaBean code:

(1) No public modifier required

As previously stated, groovy's default access modifier is public, and you don't have to write it if your groovy class members need public adornments.

(2) No type description required

As I said before, groovy does not care about the specific types of variables and method parameters.

(3) No Getter/setter method required

Not surprisingly, many Ides, such as Eclipse, have long been able to automatically generate Getter/setter methods for the sequencer. In groovy, there is absolutely no need for the Getter/setter method-all Class members (if default public) do not reference them at all through the Getter/setter method (of course, if you must access member properties through the Get/set method), Groovy also provides them).

(4) No constructors required

Do not require programmers to declare any constructors, because groovy automatically provides enough constructors for you to use. Don't worry about not enough constructors, because you actually need only two constructors (a default constructor with no parameters, 1 constructors with only one map parameter-because it's a map type, you can initialize its member variables arbitrarily when you construct the object).

(5) No return required

In groovy, the method does not need return to return a value. This seems hard to understand. Look at the code behind it.

So the groovy style class is this:

(6) No need () No.

In groovy, the method call can omit the () number (except the constructor), which means that the following two sentences are equivalent:

Person1.setname ' KK '
person1.setname (' KK ')

Let's look at an example of a complete class definition:

Class Person {
    def name
    def-age
    string toString () {//Note the type of method string, because the method we are overriding is the string type
        "$name, $age"
    }
}

We can instantiate the person class using the default construction method:
def person1 = new Person ()
person1.name= ' KK '
person1.age=20
println Person1

//can also do the same thing in groovy style:
def person2 = new Person ([' name ': ' GG ', ' age ':])    //[] Number can be omitted
println Person2

Print as follows:

kk,20
gg,22

It is important to note that we have overridden the ToString method of object because we want to simply print the object's property value by Println Person1.

However, the ToString method does not return a string, but it does not worry that Groovy returns the value of the last line of the method by default. 14,. Operator

In Java, sometimes to avoid null pointer anomalies, we usually need this technique:

if (rs!=null) {
       rs.next () ...

}

In groovy, you can use the? operator to achieve the same purpose:

Rs?. Next ()

? Here is a conditional operator, if the preceding object is not NULL, execute the following method, or do nothing.

15. Variable length parameter
Equivalent to the variable-length parameter in Java 5. First we define a method of variable-length parameters sum:

int sum (int ... var) {def total
    = 0
    for (i-VAR) total
        + = i
    return total
}

//We can use any number of arguments when we call sum Number (one, 2, 3 ...) ):

println sum (1)
println sum (
println sum)
println sum (1,2,9,10,55)

16. Enumeration

1. Define a Enum:enum day {SUNDAY, MONDAY, Tuesday, Wednesday, Thursday, FRIDAY, SATURDAY}//2, and then we use him in the switch statement: def today = Day.saturday switch (today) {//saturday or Sunday case [Day.saturday, Day.sunday]: println "Wee Kends is cool "break//a day between Monday and Friday case Day.monday. Day.FRIDAY:println ' boring work day ' break Default:println ' is your sure this was a valid day

?"
}

3. Note that you can use any object in switch and case, especially if you can use list and scope in case, so that the branch satisfies multiple conditions (which is a bit like Delphi).
    4. Like Java5, groovy supports enum:enum with constructors, properties, and methods Planet {MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27,7.1492e7), SATURN (5.688e+26, 6.0268e7 ), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7) Double mass double radius Planet (double
        Mass, double radius) {this.mass = mass;
    This.radius = radius; } void PrintMe () {println "${name ()} has a mass of ${mass}" + "and a radius of ${radius}"}} Planet.ea Rth.printme () Planet.JUPITER.printMe ()

Print as follows:

Weekends is cool
EARTH has a mass of 5.976E24 and a radius of 6378140.0
JUPITER have a mass of 1.9E27 and a radius of 7.1492E7
17. Elvis operator

This is a simple form of a trinocular operator "?:", and the trinocular operator usually appears in this form:

String DisplayName = name! = null? Name: "Unknown";

In groovy, it can also be simplified as (because null can be converted to a Boolean value in Groovy):

String displayName = name? Name: "Unknown";

Based on the principle of "no repetition", you can use the Elvis operator again to simplify:

String displayName = name?: "Unknown"
18. Dynamic Nature

Groovy all objects have a meta-class metaclass, and we can access the meta-class through the Metaclass property. With a meta-class, you can add a method to this object (unthinkable in Java). See the following code, MSG is a string, through the meta class, we add a string class to msg that does not have a method up:

def msg = "Hello!"
println Msg.metaclass
String.metaClass.up = {  delegate.touppercase ()}
println msg.up ()

//2, via Meta class, We can also retrieve the methods and properties owned by the object (like reflection):
Msg.metaClass.methods.each {println It.name}
Msg.metaClass.properties.each { println It.name}

//3, even we can see the up method we just added.
//4, we can judge by the meta-class there is a method called up, and then call it:

if (Msg.metaClass.respondsTo (msg, ' up ')) {
    println msg.touppercase ()
}

//5, of course, it can also be inferred that it has a property called bytes:

if (Msg.metaClass.hasProperty (msg, ' bytes ')) {
    println Msg.bytes.encodeBase64 ()
}

Reference acknowledgements:
(1), Groovy Introductory tutorial
(2), groovy language Specification-syntax
(3), official grammar

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.