groovy语法篇介绍

时间:2022-03-21 10:16:12

        学习gradle的过程中,发现这东西的脚本虽然能看懂,但是不知道为什么那样,很多语法都是莫名其妙的,想来,想学会这gradle光会java可不行,于是乎便想起,gradle是一groovy为基础面向java应用为主的一种构建工具,那么很显然gradle中很多东西都是来自groovy的了,好吧,看来还是躲不过,gradle暂且搁置,先把groovy学个大概,再来研究gradle。

        首先百度科普一下groovy的知识:

         Groovy是一种基于JVMJava虚拟机)的敏捷开发语言,它结合了PythonRubySmalltalk的许多强大的特性,Groovy 代码能够与 Java 代码很好地结合,也能用于扩展现有代码。由于其运行在 JVM 上的特性,Groovy 可以使用其他 Java 语言编写的库。

         Groovy 是 用于Java虚拟机的一种敏捷的动态语言,它是一种成熟的面向对象编程语言,既可以用于面向对象编程,又可以用作纯粹的脚本语言。使用该种语言不必编写过多的代码,同时又具有闭包和动态语言中的其他特性。

         Groovy是 JVM的一个替代语言(替代是指可以用 Groovy 在Java平台上进行 Java 编程),使用方式基本与使用 Java代码的方式相同,该语言特别适合与 Spring的动态语言支持一起使用,设计时充分考虑了Java集成,这使 Groovy 与 Java 代码的互操作很容易。(注意:不是指Groovy替代java,而是指Groovy和java很好的结合编程。

        这么看来groovy还是非常强大的,ok,现在开始groovy语法的学习。


Syntax(语法)

This chapter covers the syntax of the Groovy programming language.The grammar of the language derives from the Java grammar,but enhances it with specific constructs for Groovy, and allows certain simplifications.

本篇文章讲述了groovy编程语言的语法。这个语言的语法来自于java语法,但是增强了groovy的具体构建,并且允许一定程度的简化。


1. Comments(注释)

1.1. Single line comment(单行注释)

Single line comments start with // and can be found at any position in the line.The characters following//, till the end of the line, are considered part of the comment.

单行注释以//开始,可以被放置在一行的任意位置。在//之后的字符,直到这一行的结束,都是注释的一部分。

// a standalone single line comment
println
"hello" // a comment till the end of the line

1.2. Multiline comment(多行注释)

A multiline comment starts with /* and can be found at any position in the line.The characters following/* will be considered part of the comment, including new line characters,up to the first*/ closing the comment.Multiline comments can thus be put at the end of a statement, or even inside a statement.

多行注释以/*开始,可以被放置在一行的任意位置。在/*后面*/上面的字符将会被认为是注释的一部分,包括新的一行字符(跟java一样,在两者之间)。因此,多行注释可以被放置在一个语句的后面,甚至是一个语句的里面

/* a standalone multiline comment
spanning two lines */

println
"hello" /* a multiline comment starting
at the end of a statement */

println
1 /* one */ + 2 /* two */

1.3. GroovyDoc comment(groovy文档注释)

Similarly to multiline comments, GroovyDoc comments are multiline, but start with/** and end with */.Lines following the first GroovyDoc comment line can optionally start with a star*.Those comments are associated with:

  • type definitions (classes, interfaces, enums, annotations),

  • fields and properties definitions

  • methods definitions

Although the compiler will not complain about GroovyDoc comments not being associated with the above language elements,you should prepend those constructs with the comment right before it.

类似于多行注释,groovy文档注释也是多行的,但是确实以/**开始,以*/结尾。在第一个groovy文档注释行之后,可以随意的用一个*打头。那些注释被用于:

  • 类型定义 (classes, interfaces, enums, annotations),

  • 变量和属性定义

  • 方法定于

尽管编译器不会在意关联上面的语言没有被关联到注释上,但是在那之前你应该预先考虑将那些语言构造增加到注释的右边。


/**
* A Class description
*/

class Person {
/** the name of the person */
String name

/**
* Creates a greeting method for a certain person.
*
* @param otherPerson the person to greet
* @return a greeting message
*/

String greet(String otherPerson) {
"Hello ${otherPerson}"
}
}

GroovyDoc follows the same conventions as Java’s own JavaDoc.So you’ll be able to use the same tags as with JavaDoc.

groovy文档与java一样遵循相同的约束,所以你就可以使用与java相同的标记了。


1.4. Shebang line

Beside the single line comment, there is a special line comment, often called theshebang line understood by UNIX systems which allows scripts to be run directly from the command-line, provided you have installed the Groovy distributionand thegroovy command is available on the PATH.

和单行注释相比,有一个特殊的行注释,在UNIX系统中通常被称作shebang,允许直接从命令行运行脚本。前提是你已经安装了groovy,并且groovy的命令路径是可用的。

#!/usr/bin/env groovy
println
"Hello from the shebang line"
  The # character must be the first character of the file. Any indentation would yield a compilation error.
#字符必须是文件的第一个字符,任何的缩进都会导致编译错误。


2. Keywords(关键字)

The following list represents all the keywords of the Groovy language:

下面是被列举出来的所有的groovy关键字:

Table 1. Keywords

as

assert

break

case

catch

class

const

continue

def

default

do

else

enum

extends

false

finally

for

goto

if

implements

import

in

instanceof

interface

new

null

package

return

super

switch

this

throw

throws

trait

true

try

while

   


3. Identifiers(标识符,包括方法名和变量名以及常量名等

3.1. Normal identifiers(一般标识符)

Identifiers start with a letter, a dollar or an underscore.They cannot start with a number.

标识符可以以一个字母、$(美元符号)或者下划线开头。它们不能以数字开头

A letter can be in the following ranges:

字母可以是以下范围:

  • 'a' to 'z' (lowercase ascii letter)

  • 'A' to 'Z' (uppercase ascii letter)

  • '\u00C0' to '\u00D6'

  • '\u00D8' to '\u00F6'

  • '\u00F8' to '\u00FF'

  • '\u0100' to '\uFFFE'

Then following characters can contain letters and numbers.

除了第一个字母,接下来的字符可以包含字母和数字。

Here are a few examples of valid identifiers (here, variable names):

这里是一些合法标识符的例子(合法的变量名):

def name
def item3
def with_underscore
def $dollarStart

But the following ones are invalid identifiers:

但是下面一些都是不合法的标识符:

def 3tier
def a+b
def a#b
All keywords are also valid identifiers when following a dot:

所有的关键字也是有效的标识符当它们出现在一个点后面的时候:

foo.as
foo
.assert
foo
.break
foo
.case
foo
.catch

3.2. Quoted identifiers(带引号的标识符)

Quoted identifiers appear after the dot of a dotted expression.For instance, thename part of the person.name expression can be quoted withperson."name" or person.'name'.This is particularly interesting when certain identifiers contain illegal characters that are forbidden by the Java Language Specification,but which are allowed by Groovy when quoted. For example, characters like a dash, a space, an exclamation mark, etc.

带引号的标识符出现在带点的表达式的点的后面,例如,person.name表达式的name部分,可以被加上引号变成person."name" 或者是person.'name'。特别需要注意的是,一些java语言中明确规定的不合法字符,但是在groovy中通过加上引号是被允许的。例如,像dash、空格、感叹号等等。


def map = [:]

map
."an identifier with a space and double quotes" = "ALLOWED"
map
.'with-dash-signs-and-single-quotes' = "ALLOWED"

assert map."an identifier with a space and double quotes" == "ALLOWED"
assert map.'with-dash-signs-and-single-quotes' == "ALLOWED"

As we shall see in the following section on strings, Groovy provides different string literals.All kind of strings are actually allowed after the dot:

我们将要在下面的章节中看到字符串,groovy提供了不同的字符串。所有的字符串都被允许在一个点的后面:

map.'single quote'
map
."double quote"
map
.'''triple single quote'''
map
."""triple double quote"""
map
./slashy string/
map
.$/dollar slashy string/$
There’s a difference between plain character strings and Groovy’s GStrings (interpolated strings),as in that the latter case, the interpolated values are inserted in the final string for evaluating the whole identifier:
这是一个普通字符串和groovy的GString(插入字符串)字符串的区别,作为后者的情况下,插入一个改变的值到不变的string中来决定整个标识符的值:

def firstname = "Homer"
map
."Simson-${firstname}" = "Homer Simson"

assert map.'Simson-Homer' == "Homer Simson"
未完待续……