Series of articles look here

Gradle gets started and builds the environment

Gradle is an introduction to meta-programming

Gradle: Groovy syntax for getting started

Gradle introduction and lifecycle

Gradle core project

How to create a Gradle plugin by yourself

What is a Transform in Gradle?

preface

Gradle is a JVM-based build tool that combines many of the powerful features of Python, Ruby, and Smalltalk. Groovy code works well with Java code and can be used to extend existing code. Because of its nature running on the JVM, Groovy can use libraries written in other Java languages. At present, it has been applied in most Android technology systems, such as Jenkins, plug-in, component, modular and so on. If you don’t know Gradle, the first few technical points are hard to understand.

Groovy’s syntax is similar to Kotlin’s, and it would be much easier to learn Groovy if we had Kotlin’s experience. Let’s take a look at groovy’s core syntax.

The basic characteristics of

  • Built on top of the powerful Java language, it adds features learned from languages like Python, Ruby, and Smalltalk, such as dynamic type conversion, closures, and metaprogramming support.
  • Provides Java developers with some of the most popular programming language features in modern times at a low cost (almost zero) to learn.
  • Support for DSL (Domain Specific Languages Domain Definition Language) and other concise syntax, making code easy to read and maintain.
  • Checked exceptions can also be omitted.
  • Groovy’s handling of native types, object-oriented, and an Ant DSL makes creating Shell Scripts very simple.
  • You can greatly improve your productivity by reducing the amount of boilerplate code you use when developing Web, GUI, database, or console applications.
  • Support for unit tests and mocks (objects) to simplify testing.
  • Seamlessly integrate all existing Java objects and class libraries.
  • Directly compiled to Java bytecode, Groovy can be used anywhere Java is used.
  • Support for functional programming, no main function required.
  • Some new operators.
  • Commonly used packages are imported by default.
  • Assertions do not support switching the -EA parameter of the JVM.
  • Supports Boolean evaluation of objects.
  • Classes do not support the default scope, and the default scope is public.
  • Basic types in Groovy are also objects, and you can call their methods directly.

Basic grammar

Variables in Groovy

Variables in Groovy can be strongly typed, like Java, or weakly typed, like Kotlin. A code example is as follows:

class Study {
    static void main(String[] args) {
        String a = 'Hello World'
        def b = "Hello Silence"
        println(a)
        println(b)
    }
}
Copy the code

The following output is displayed:

Hello World
Hello Silence
Copy the code

Operators and conditional controls in Groovy

Consistent with Java, not covered here

Strings in Groovy

Groovy provides several ways to represent String literals. Strings in Groovy can be enclosed in single (‘), double (“), or triple (” “) quotes. In addition, Groovy strings enclosed in triple quotes can span multiple lines.

Example code is as follows:

class Study {
    static void main(String[] args) {
        String a = 'Hello World'
        def b = "Hello Silence"
        def c = '''Hello World
Hello Silence'''
        println(a)
        println(b)
        println(c)
    }
}
Copy the code

The running results are as follows:

Hello World
Hello Silence
Hello World
Hello Silence
Copy the code
String extension

Groovy’s extension is the same as Kotlin’s, with the following example code:

class Study {
    static void main(String[] args) {
        String a = 'Hello World'
        def b = "Hello $a"
        println(a)
        println(b)
    }
}
Copy the code

The following output is displayed:

Hello World
Hello Hello World
Copy the code
Index of string

Strings in Groovy are ordered sequences of characters. Individual characters in a string can be accessed by their positions. This is given by the index position.

The string index starts at zero and ends with a value less than the length of the string. Groovy also allows negative indexes to count from the end of the string.

The specific code is as follows:

Class Study {static void main(String[] args) {String a = 'Hello World' println(a[1] Println (a) [2] / / output the contents of the coordinates of the penultimate println (a) [1.. 2] / / the contents of the output coordinate interval is 1-2 println (a) [2.. 5] / / the contents of the output coordinate interval is 2-5}}Copy the code

The following output is displayed:

e
l
el
llo 
Copy the code

The data structure

Scope of the Range

A range is shorthand for specifying a sequence of values. Ranges are represented by the first and last values in a sequence, and Range can be included or excluded. An inclusion range includes all values from the first to the last, while an exclusive range includes all values except the last.

  • 1.. 10 – Contains examples of ranges
  • 1.. <10 – Example of exclusive scope
  • ‘a’.. ‘x’ – ranges can also be composed of characters
  • 10.. 1 – Ranges can also be sorted in descending order
  • ‘x’.. ‘A’ – ranges can also be composed of characters and arranged in descending order.

List

A list is a structure used to store a collection of data items. In Groovy, a List holds a List of object references.

Object references in the List occupy positions in the sequence and are distinguished by integer indexes.

The data in a list in Groovy can be of any type. This is a bit different from Java collection lists, which are collections of the same type of data.

Lists can also be nested in Groovy. For example,[1,2,[3,4,5], “aaa”]groovy lists have the built-in reverse() method. A call to list.reverse () can reverse the List. Groovy lists have a built-in sorting method called sort(). You can sort a List by calling list.sort (). An empty list is denoted by [] to declare an empty collection.

Map

A Map is an unordered collection of object references. Elements in the Map collection are accessed by key values. The keys used in the Map can be any class. When we insert into the Map collection, we need two values: the key and the value.

object-oriented

The three major characteristics

In Groovy, as in any other object-oriented language, there are concepts of classes and objects. However, a new trait keyword has been added to Groovy called Features.

Features in Groovy

Features are the construction of language structures, others include:

  • Composition of behavior
  • Implementation of the interface runtime
  • Compatibility with static type checking/compilation

Use the trait keyword to define traits. Example code is as follows:

class Study {
    static void main(String[] args) {
        Student st = new Student();
        st.StudentID = 1
        st.Marks1 = 10
        st.DisplayMarks()
    }
}

trait Marks {
    void DisplayMarks() {
        println("Display Marks")
    }
}

class Student implements Marks {
    int StudentID
    int Marks1
}
Copy the code

The following output is displayed:

Display Marks
Copy the code

In the same way that traits exist as interfaces in the example above, traits can also implement interfaces. Example code is as follows:

class Study { static void main(String[] args) { Student st = new Student(); st.StudentID = 1 st.Marks1 = 10 st.DisplayMarks() st.DisplayTotal() } } interface Total { void DisplayTotal() } trait Marks implements Total { void DisplayMarks() { println("Display Marks") } void DisplayTotal() { println("Display Total")  } } class Student implements Marks { int StudentID int Marks1 }Copy the code

The following output is displayed:

Display Marks
Display Total
Copy the code

Extension features

An extension of a feature uses the extends keyword, as shown in the following example:

trait Marks { void DisplayMarks() { println("Marks1"); } } trait Total extends Marks { void DisplayMarks() { println("Total"); }}Copy the code

Closures in Groovy

Closures are short, anonymous blocks of code, similar to lamda. Here is a simple closure example with the following code:

class Study {
    static void main(String[] args) {
        def test = { println "Hello World" }
        test.call()
    }
}
Copy the code

The following output is displayed:

Hello World
Copy the code

Formal parameters in closures

Closures can also contain formal parameters to make them more useful, just like the methods in Groovy.

class Study {
    static void main(String[] args) {
        def hello="Hello"
        def test = {params -> println "$hello World" }
        test.call()
    }
}
Copy the code

The output is also Hello World. And of course we have another way of writing it:

class Study {
    static void main(String[] args) {
        def test = { println "Hello ${it}" }
        test.call("World")
    }
}
Copy the code

We can also combine the above two forms as shown in the following example:

class Study {
    static void main(String[] args) {
        def hello="Hello"
        def test = { params ->println "$hello ${params}" }
        test.call("World")
    }
}
Copy the code

Use closures in methods

Similar to kotlin’s method can pass anonymous functions. Example code is as follows:

class Study {
    static void main(String[] args) {
        def hello="Hello"
        def test = { params ->println "$hello ${params}" }
        Study.Display(test)
    }

    def static Display(clo) {
        clo.call("Silence")
    }
}
Copy the code

The following output is displayed:

Hello Silence
Copy the code

In the Groovy Json

Let’s take a look at converting objects to JSON strings in Groovy:

import groovy.json.JsonOutput class Study{ public static void main(String[] args) { def study = [new Person("silence", 25), new Person("david", 26)] def json= jsonoutput. toJson(study) println json println jsonoutput. prettyPrint(json)}} class Person {  private String name private int age Person(String name, int age) { this.name = name this.age = age } String getName() { return name } void setName(String name) { this.name = name } int getAge() { return age } void setAge(int age) { this.age = age } }Copy the code

The following output is displayed:

[{"age":25,"name":"silence"},{"age":26,"name":"david"}]
[
    {
        "age": 25,
        "name": "silence"
    },
    {
        "age": 26,
        "name": "david"
    }
]
Copy the code

conclusion

This article focuses on the basic groovy syntax, which is generally similar to kotlin’s and Java’s syntax. Those familiar with Kotlin and Java will be relatively quick to pick up groovy.

reference

Gradle Automation Project Building (ii) – Groovy core syntax tutorial

This post was first published on my blog: Gradle 101: Groovy Syntax

More articles please pay attention to my public number: code nong workplace