Groovy基本句法

2024-04-28 00:18
文章标签 基本 groovy 句法

本文主要是介绍Groovy基本句法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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 commentspanning two lines */
println "hello" /* a multiline comment startingat 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 = /onetwothree/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基本句法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/941875

相关文章

Python中多线程和多进程的基本用法详解

《Python中多线程和多进程的基本用法详解》这篇文章介绍了Python中多线程和多进程的相关知识,包括并发编程的优势,多线程和多进程的概念、适用场景、示例代码,线程池和进程池的使用,以及如何选择合适... 目录引言一、并发编程的主要优势二、python的多线程(Threading)1. 什么是多线程?2.

MyBatis-Flex BaseMapper的接口基本用法小结

《MyBatis-FlexBaseMapper的接口基本用法小结》本文主要介绍了MyBatis-FlexBaseMapper的接口基本用法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具... 目录MyBATis-Flex简单介绍特性基础方法INSERT① insert② insertSelec

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

使用Python进行文件读写操作的基本方法

《使用Python进行文件读写操作的基本方法》今天的内容来介绍Python中进行文件读写操作的方法,这在学习Python时是必不可少的技术点,希望可以帮助到正在学习python的小伙伴,以下是Pyth... 目录一、文件读取:二、文件写入:三、文件追加:四、文件读写的二进制模式:五、使用 json 模块读写

基本知识点

1、c++的输入加上ios::sync_with_stdio(false);  等价于 c的输入,读取速度会加快(但是在字符串的题里面和容易出现问题) 2、lower_bound()和upper_bound() iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。 iterator upper_bou

【IPV6从入门到起飞】5-1 IPV6+Home Assistant(搭建基本环境)

【IPV6从入门到起飞】5-1 IPV6+Home Assistant #搭建基本环境 1 背景2 docker下载 hass3 创建容器4 浏览器访问 hass5 手机APP远程访问hass6 更多玩法 1 背景 既然电脑可以IPV6入站,手机流量可以访问IPV6网络的服务,为什么不在电脑搭建Home Assistant(hass),来控制你的设备呢?@智能家居 @万物互联

C 语言的基本数据类型

C 语言的基本数据类型 注:本文面向 C 语言初学者,如果你是熟手,那就不用看了。 有人问我,char、short、int、long、float、double 等这些关键字到底是什么意思,如果说他们是数据类型的话,那么为啥有这么多数据类型呢? 如果写了一句: int a; 那么执行的时候在内存中会有什么变化呢? 橡皮泥大家都玩过吧,一般你买橡皮泥的时候,店家会赠送一些模板。 上

FreeRTOS-基本介绍和移植STM32

FreeRTOS-基本介绍和STM32移植 一、裸机开发和操作系统开发介绍二、任务调度和任务状态介绍2.1 任务调度2.1.1 抢占式调度2.1.2 时间片调度 2.2 任务状态 三、FreeRTOS源码和移植STM323.1 FreeRTOS源码3.2 FreeRTOS移植STM323.2.1 代码移植3.2.2 时钟中断配置 一、裸机开发和操作系统开发介绍 裸机:前后台系

Java 多线程的基本方式

Java 多线程的基本方式 基础实现两种方式: 通过实现Callable 接口方式(可得到返回值):