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

相关文章

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 岁

mysql中insert into的基本用法和一些示例

《mysql中insertinto的基本用法和一些示例》INSERTINTO用于向MySQL表插入新行,支持单行/多行及部分列插入,下面给大家介绍mysql中insertinto的基本用法和一些示例... 目录基本语法插入单行数据插入多行数据插入部分列的数据插入默认值注意事项在mysql中,INSERT I

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

MyBatis ResultMap 的基本用法示例详解

《MyBatisResultMap的基本用法示例详解》在MyBatis中,resultMap用于定义数据库查询结果到Java对象属性的映射关系,本文给大家介绍MyBatisResultMap的基本... 目录MyBATis 中的 resultMap1. resultMap 的基本语法2. 简单的 resul

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

git stash命令基本用法详解

《gitstash命令基本用法详解》gitstash是Git中一个非常有用的命令,它可以临时保存当前工作区的修改,让你可以切换到其他分支或者处理其他任务,而不需要提交这些还未完成的修改,这篇文章主要... 目录一、基本用法1. 保存当前修改(包括暂存区和工作区的内容)2. 查看保存了哪些 stash3. 恢

MySQL基本查询示例总结

《MySQL基本查询示例总结》:本文主要介绍MySQL基本查询示例总结,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Create插入替换Retrieve(读取)select(确定列)where条件(确定行)null查询order by语句li

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async