Groovy基本句法

Gradle作为一个构建工具自然不会自己去创造一门语言来支撑自己,那么它用的是哪门子语言呢?什么语言能写成这样:

task hello {
doLast {
println 'Hello world!'
}
}

如此风骚的语法自然要归Groovy莫属了。

什么是Groovy

官方介绍如下:

Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

大概意思是Groovy是一门运行在java平台上的强大的、可选类型的、动态语言。使用Groovy可以使你的应用具备脚本,DSL定义,运行时和编译时元编程,函数式编程等功能。

接下来将分几个小节简单介绍Groovy的语法规范。

Groovy语法

注释

Groovy使用的注释有一下几种:

1.单行注释

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

2.多行注释

/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */

3.文档注释

/**
* 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}"
}
}

4.组织行

#!/usr/bin/env groovy
println "Hello from the shebang line"

这类脚本注释主要用于表明脚本的路径。

字符串

单引号字符串

单引号字符串对应java中的String,不支持插入。

'a single quoted string'

字符串连接

assert 'ab' == 'a' + 'b'

三引号字符串

'''a triple single quoted string'''

三引号字符串同样对应java中的String,不支持动态插入。三引号字符串支持多行:

def aMultilineString = '''line one
line two
line three'''

转义

Groovy中使用\来进行转义

'an escaped single quote: \' needs a backslash'

双引号字符串

"a double quoted string"

如果双引号字符串中没有插入表达式的话对应的是java中的String对象,如果有则对应Groovy中的GString对象。

Groovy中使用${}来表示插入表达式,$来表示引用表达:

def name = 'Guillaume' // a plain string
def greeting = "Hello ${name}" assert greeting.toString() == 'Hello Guillaume'
def person = [name: 'Guillaume', age: 36]
assert "$person.name is $person.age years old" == 'Guillaume is 36 years old'
shouldFail(MissingPropertyException) {
println "$number.toString()"
}

插入闭包表达式

def sParameterLessClosure = "1 + 2 == ${-> 3}"
assert sParameterLessClosure == '1 + 2 == 3' def sOneParamClosure = "1 + 2 == ${ w -> w << 3}"
assert sOneParamClosure == '1 + 2 == 3'
def number = 1
def eagerGString = "value == ${number}"
def lazyGString = "value == ${ -> number }" assert eagerGString == "value == 1"
assert lazyGString == "value == 1" number = 2
assert eagerGString == "value == 1"
assert lazyGString == "value == 2"

关于闭包,暂时先看看就行,等后面具体学习完闭包以后再回来看这几个表达式就简单了。

三双引号字符串

def name = 'Groovy'
def template = """
Dear Mr ${name}, You're the winner of the lottery! Yours sincerly, Dave
""" assert template.toString().contains('Groovy')

斜杠字符串

Groovy也可以使用/来定义字符串,主要用于正则表达式

def fooPattern = /.*foo.*/
assert fooPattern == '.*foo.*'
def escapeSlash = /The character \/ is a forward slash/
assert escapeSlash == 'The character / is a forward slash'
def multilineSlashy = /one
two
three/ assert multilineSlashy.contains('\n')
def color = 'blue'
def interpolatedSlashy = /a ${color} car/ assert interpolatedSlashy == 'a blue car'

\(/和/\)字符串

def name = "Guillaume"
def date = "April, 1st" def dollarSlashy = $/
Hello $name,
today we're ${date}. $ dollar sign
$$ escaped dollar sign
\ backslash
/ forward slash
$/ escaped forward slash
$/$ escaped dollar slashy string delimiter
/$ assert [
'Guillaume',
'April, 1st',
'$ dollar sign',
'$ escaped dollar sign',
'\\ backslash',
'/ forward slash',
'$/ escaped forward slash',
'/$ escaped dollar slashy string delimiter' ].each { dollarSlashy.contains(it) }

字符

单引号字符串如果只有一个字符会被转化成char类型。

列表

Groovy中列表使用[]表示,其中可以包含任意类型的元素:

def heterogeneous = [1, "a", true]

使用下标进行取值和赋值

def letters = ['a', 'b', 'c', 'd']

assert letters[0] == 'a'
assert letters[1] == 'b' assert letters[-1] == 'd'
assert letters[-2] == 'c' letters[2] = 'C'
assert letters[2] == 'C' letters << 'e'
assert letters[ 4] == 'e'
assert letters[-1] == 'e' assert letters[1, 3] == ['b', 'd']
assert letters[2..4] == ['C', 'd', 'e']

数组

Groovy中复用List来充当数组,但如果要明确定义真正的数组需要使用类似java的定义方法

String[] arrStr = ['Ananas', 'Banana', 'Kiwi']  

assert arrStr instanceof String[]
assert !(arrStr instanceof List) def numArr = [1, 2, 3] as int[] assert numArr instanceof int[]
assert numArr.size() == 3

键值数组

Groovy中键值数组使用如下

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']   

assert colors['red'] == '#FF0000'
assert colors.green == '#00FF00' colors['pink'] = '#FF00FF'
colors.yellow = '#FFFF00' assert colors.pink == '#FF00FF'
assert colors['yellow'] == '#FFFF00' assert colors instanceof java.util.LinkedHashMap

以上简单列举了Groovy的基本语法,想要深入学习的可以参考以下网址:

运行syntax.groovy查看实例及运行结果

安装Groovy参考如下:

http://www.groovy-lang.org/download.html

Groovy基本句法的更多相关文章

  1. Groovy中的脚本与类

    包名 当你在groovy中定义类的时候需要指定包名,这和java中类似不多介绍. 导入 groovy中的导入也跟java类似,有一下五种: 默认导入 groovy默认导入了一下几个包和类: impor ...

  2. groovy语法

    1.注释1.1. 单行注释1.2. 多行注释1.3. GroovyDoc注释1.4. Shebang线2.关键词3.标识符3.1. 普通标识符3.2. 带引号的标识符4.字符串4.1. 单引号字符串4 ...

  3. Groovy中的闭包

    Closures(闭包) 本节主要讲groovy中的一个核心语法:closurs,也叫闭包.闭包在groovy中是一个处于代码上下文中的开放的,匿名代码块.它可以访问到其外部的变量或方法. 1. 句法 ...

  4. Groovy sort() list

    https://www.w3cschool.cn/groovy/groovy_sort.html #Groovy sort()方法返回原始列表的排序副本. #句法List sort() #参数没有 # ...

  5. Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)

    这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...

  6. 用Groovy构建java脚本

    我是做工作流项目的,工作流中各个模板引擎都需要要执行一个动态业务,这些动态业务有多种实现方式,最常用的就是用户自己写一段脚本文件,然后工作流引擎执行到这里的时候,运行这个脚本文件. 这个运行脚本文件的 ...

  7. Groovy学习--基本语法了解

    x项目用到gradle,学习gradle之前准备先过一遍Groovy的语法.这里参考:Groovy入门. 该博客没有系统的讲解Groovy的语法和原理,仅仅只是罗列了使用Groovy的常规方法.我照着 ...

  8. How to use groovy script on jenkins

    1. Install groovy plugin 2. Add a step of groovy. (normal & systerm) 3. Execute groovy script im ...

  9. Java8-Function使用及Groovy闭包的代码示例

    导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...

随机推荐

  1. Node.js + Express + Ubuntu

    1 . 怎么在ubuntu中,background的方式 启动express. 网站www /home/host/express/web/bin# nohup node www 2. Node.js的 ...

  2. Mybatis(一):MyBatis配置文件config.xml详解

    MyBatis 配置文件基本结构 在使用mybatis框架时,首先导入其对应的jar包,并进行相应的配置,所以得对配置文件的每个参数都得了解.一个完全的mybatis配置文件结构如下: <?xm ...

  3. 【打CF,学算法——二星级】Codeforces Round #313 (Div. 2) B. Gerald is into Art(水题)

    [CF简单介绍] 提交链接:http://codeforces.com/contest/560/problem/B 题面: B. Gerald is into Art time limit per t ...

  4. Centos7 安装Git-cola

    首先安装Git sudo yum -y install git* 找到 git-all.noarch , 安装这个. sudo yum install git-all.noarch ========= ...

  5. shell取余数

    shell取余数 技术分享 » linux | 阅读(9993) | 评论(0) Sep 3 2010 备忘脚本date取得分钟数$(()) 运算 #execute every 5 minutesa= ...

  6. private继承的作用

    这里有个demo,里面的Stack<T*> : private Stack<void *>,作者对此的解释如下 The partial specialization for o ...

  7. spark源码 hashpartitioner

    def nonNegativeMod(x: Int, mod: Int): Int = { val rawMod = x % mod rawMod + () mod ) def getPartitio ...

  8. C++中类所占的存储空间

    #include <iostream> using namespace std; class A { int m_a; int get() { return m_a; } virtual ...

  9. 一次完整的https过程

    参考: 1. 一次完整的HTTP事务是怎样一个过程? 2. The First Few Milliseconds of an HTTPS Connection 3. 也许,这样理解HTTPS更容易 4 ...

  10. I2C和SPI

    I2C(Inter-Integrated Circuit)总线 两线式串行总线,用于连接微控制器及其外围设备.是微电子通信控制领域广泛采用的一种总线标准.它是同步通信的一种特殊形式,具有接口线少,控制 ...