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 ORM神器之SQLAlchemy基本使用完全指南

《PythonORM神器之SQLAlchemy基本使用完全指南》SQLAlchemy是Python主流ORM框架,通过对象化方式简化数据库操作,支持多数据库,提供引擎、会话、模型等核心组件,实现事务... 目录一、什么是SQLAlchemy?二、安装SQLAlchemy三、核心概念1. Engine(引擎)

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

Go语言连接MySQL数据库执行基本的增删改查

《Go语言连接MySQL数据库执行基本的增删改查》在后端开发中,MySQL是最常用的关系型数据库之一,本文主要为大家详细介绍了如何使用Go连接MySQL数据库并执行基本的增删改查吧... 目录Go语言连接mysql数据库准备工作安装 MySQL 驱动代码实现运行结果注意事项Go语言执行基本的增删改查准备工作

DNS查询的利器! linux的dig命令基本用法详解

《DNS查询的利器!linux的dig命令基本用法详解》dig命令可以查询各种类型DNS记录信息,下面我们将通过实际示例和dig命令常用参数来详细说明如何使用dig实用程序... dig(Domain Information Groper)是一款功能强大的 linux 命令行实用程序,通过查询名称服务器并输

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

SQL BETWEEN 语句的基本用法详解

《SQLBETWEEN语句的基本用法详解》SQLBETWEEN语句是一个用于在SQL查询中指定查询条件的重要工具,它允许用户指定一个范围,用于筛选符合特定条件的记录,本文将详细介绍BETWEEN语... 目录概述BETWEEN 语句的基本用法BETWEEN 语句的示例示例 1:查询年龄在 20 到 30 岁