【Groovy】变量和基本数据类型

1 变量

1)变量的声明

Groovy 复制代码
int a = 1
def b
def c = 1

​ 在脚本中定义变量无需声明变量的类型,如下。在类不能使用以下方式定义变量,否则会编译报错。

Groovy 复制代码
a = 1
b = "abc"

2)变量命名规范

  • 变量名可以由字母、数字、下划线(_)和美元符号($)组成,但是不能以数字开头,且大小写敏感。
  • 不能有空格、@、#、+、-、/ 等符号。
  • 应该使用有意义的名称,达到见名知意的目的,最好以小写字母开头。
  • 不能与 Groovy 语言的关键字或是基本数据类型重名。

3)可变类型变量

​ 使用 def 声明的变量是可变类型变量。以下变量赋值是合法的。

Groovy 复制代码
def a = new Object()
a = 1
a = 1f
a = "xyz"
a = new StringBuffer()

​ 以下变量赋值是非法的。

Groovy 复制代码
int a = 1
a = "abc"

2 基本数据类型

​ Groovy 中基本数据类型主要有空类型(void)、整数类型(byte、short、int、long、BigInteger)、浮点类型(float、double、BigDecimal)、字符类型(char)、字符串类型(String)。

2.1 空类型

2.1.1 void 和 null

​ Groovy 中空类型用 void 表示,空值用 null 表示,与 java 的使用方法一样,如下。

Groovy 复制代码
BigInteger a = null
def b = null

void fun1() {
    /***/
}

Object fun2() {
    return null
}

2.1.2 安全访问符(?.)

​ 安全访问符(?.)用于告诉编译器:如果对象非空才访问点后面的内容,否则不做任何处理。

Groovy 复制代码
String a = "abc"
println(a?.substring(1)) // 打印: bc

String b = null
println(b?.substring(1)) // 打印: null

2.1.3 Elvis 运算符(?:)

​ Elvis 运算符(?:)用于告诉编译器:如果 ?: 前面的值为 null,就取 ?: 后面的值。

Groovy 复制代码
String a = "abc"
String b = a ?: "xyz"
println(b) // 打印: abc

String c = null
String d = c ?: "xyz"
println(d) // 打印: xyz

2.2 数字类型

2.2.1 整数类型

1)整数类型变量

类型 大小(位) 最小值 最大值 案例
byte 8 -128 127 byte a = 1
short 16 -32768 32767 short a = 1
int 32 -2,147,483,648 (-2^31) 2,147,483,648(2^31-1) int a = 1 def a = 100 def a = 100I def a = 100i
long 64 -9,223,372,036,854,775,808(-2^63) 9,223,372,036,854,775,807 (2^63-1) long a = 1 def a = 12345678901 def a = 100L def a = 100l
BigInteger ------ ------ ------ BigInteger a = 1 def a = new BigInteger('123') def a = 1G def a = 1g

2)整数的进制表示

Groovy 复制代码
// 二进制(以0b开头)
def a = 0b101
// 八进制(以0开头)
def a = 0765
// 十六进制(以0x开头)
def a = 0x8af

3)数字分割

Groovy 复制代码
def a = 1_23_456_7
def b = 1.23_456_7
def c = 0xFF_FF_FF

4)times

Groovy 复制代码
4.times {
    println(it) // 打印: 0、1、2、3
}

4.7.times {
    println(it) // 打印: 0、1、2、3
}

​ 说明:Groovy 中的 times 函数与 Kotlin 中的 repeat 函数有些类似。

2.2.2 浮点类型

1)浮点类型变量

类型 大小(位) 符号位(S)/ 阶码(E)/ 尾数(M) 最小值/ 最大值/ 最小正数 有效位数 案例
float 32 1S + 8E + 23M -3.4028235E38 3.4028235E38 1.4E-45 6 float a = 1.0 def a = 1.0F def a = 1.0f
double 64 1S + 11E + 52M -1.7976931348623157E308 1.7976931348623157E308 4.9E-324 15 double a= 1.0 def a = 1.0D def a = 1.0d
BigDecimal ------ ------ ------ ------ BigDecimal a = 3.14 def a = new BigDecimal('3.14') def a = 3.14G def a = 3.14g

​ 浮点数编码原理详见 → 浮点数编码原理

2)浮点数科学计数法

Groovy 复制代码
double a = 1e2 // 100.0
double a = 2E1 // 20.0
double a = 2e+3 // 2000.0
double a = 3E-2 // 0.03

2.2.3 运算符

运算符 描述 作用域 优先级 案例
+ 加法 整数/浮点数 作为一元运算符时,优先级为1 作为二元运算符时,优先级为3 1 + 2 ⇒ 3
- 减法 整数/浮点数 作为一元运算符时,优先级为1 作为二元运算符时,优先级为3 1 - 2 ⇒ -1
* 乘法 整数/浮点数 2 2 * 3 ⇒ 6
/ 整除/除法 整数/浮点数 2 3 / 2 ⇒ 1 3.0 / 2 ⇒ 1.5 3 / 2.0 ⇒ 1.5
% 取余 整数/浮点数 2 7 % 3 ⇒ 1
++ 加1 整数/浮点数 1 a++(先使用, 后加1) ++a(先加1, 后使用)
-- 减1 整数/浮点数 1 a--(先使用, 后减1) --a(先减1, 后使用)
= 赋值 所有类型 9 a = 1
+= 加赋值 整数/浮点数 9 a += 1 ⇔ a = a + 1
-= 减赋值 整数/浮点数 9 a -= 2 ⇔ a = a - 2
*= 乘赋值 整数/浮点数 9 a *= 3 ⇔ a = a * 3
/= 除赋值 整数/浮点数 9 a /= 4 ⇔ a = a / 4
%= 取余赋值 整数/浮点数 9 a %= 5⇔ a = a % 5

2.3 布尔类型

2.3.1 布尔类型

类型 大小(位) 取值 案例
boolean 1 true / false boolean a = true def a = false boolean a = 100 // true boolean a = -100 // true boolean a = 0 // false

2.3.2 运算符

运算符 描述 作用域 优先级 案例
== 等于 整数/布尔/字符 1 1 == 2 // false 1 == 1 // true
!= 不等于 整数/布尔/字符 1 1 != 2 // true 1 != 1 // false
< 小于 整数/浮点数/字符 1 1 < 2 // true
> 大于 整数/浮点数/字符 1 1 > 2 // false
<= 小于等于 整数/字符 1 1 <= 2 // true
>= 大于等于 整数/字符 1 1 >= 2 // false
in 在范围内 整数/字符 1 3 in 1..9 // true 9 in 1..<9 // false
!in 不在范围内 整数/字符 1 3 !in 1..9 // false
! 布尔 2 !true // false !false // true
&& 布尔 3 true && false // false
|| 布尔 4 true || false // true

2.4 字符类型

2.4.1 字符类型

类型 大小(位) 案例
char 16 char a = 'A' def a = 'A' def a = '好' def a = '\u725B' // 牛 def a = (char) 66 // B

2.4.2 转义字符

Groovy 复制代码
\t ------ Tab制表符
\b ------ 退格
\n ------ 换行(LF)
\r ------ 回车(CR)
\' ------ 单引号
\" ------ 双引号
\\ ------ 反斜杠
\$ ------ 美元符号

2.5 字符串类型

2.5.1 字符串的定义

​ Groovy 允许实例化 java.lang.String 类定义一个字符串对象,也可以实例化 groovy.lang.GString 类定义一个字符串对象,两者可以混合编程

Groovy 复制代码
String str1 = 'abc'
def str2 = "efg"

def str3 = '''first
second'''

def str4 = """第一行
第二行"""

def str5 =/123
456/

// 字符串插值
def count = 15
def str5 = "买了${count}个苹果" // 买了15个苹果

​ 单引号(')、双引号(")、三引号(''')、三双引号(""")、斜线(/)的区别如下。

  • 单引号和三引号不支持插值、转义字符(' 和 \ 除外)、混合编程;双引号、三双引号和斜线支持插值、转义字符、混合编程。
  • 单引号和双引号不支持多行字符串;三引号、三双引号和斜线支持多行字符串(保留字符串中的换行和缩进)。

​ 通过下标即可访问字符串中元素,如下。

Groovy 复制代码
def str = "abc"
def c1 = str[0] // 'a'
def c2 = str.charAt(1) // 'b'

2.5.2 字符串函数

​ Groovy 中 String 类继承 CharSequence 类,在 _String.kt、StringsJVM.kt、StringNumberConversionsJVM.kt 等文件中定义了一些 CharSequence、String 的扩展函数。

1)判空

Groovy 复制代码
// 字符串长度是否为0 (length == 0)
public boolean isEmpty()
// 字符串中是否只存在空字符 (indexOfNonWhitespace() == length)
public boolean isBlank()

2)去掉首尾空字符

Groovy 复制代码
public String trim()

3)查找字符

Groovy 复制代码
public static String find(CharSequence self, CharSequence regex)

​ 说明:字符串查找支持正则匹配,详见 → 正则表达式(Regular Expression)详解

4)查找字符索引

Groovy 复制代码
// 从前往后查找索引
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
// 从后往前查找索引
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

5)统计字符个数

Groovy 复制代码
// 统计self中text子串的个数
public static int count(CharSequence self, CharSequence text)

6)字符串匹配

Groovy 复制代码
// 判断字符串是否以prefix开头
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toffset)
// 判断字符串是否以suffix结尾
public boolean endsWith(String suffix)

7)获取子串

Groovy 复制代码
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
public CharSequence subSequence(int beginIndex, int endIndex)

8)字符串分割

Groovy 复制代码
public String[] split(String regex)
public String[] split(String regex, int limit)
public static String[] split(CharSequence self)
public static Collection split(Object self, Closure closure)

​ 说明:字符串分割支持正则匹配,详见 → 正则表达式(Regular Expression)详解

9)字串替换

Groovy 复制代码
public static String replace(CharSequence self, Map<CharSequence, CharSequence> replacements)
public static String replaceFirst(CharSequence self, CharSequence regex, CharSequence replacement)
public static String replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement)
public static String replaceAll(CharSequence self, CharSequence regex, CharSequence replacement)
public static String replaceAll(CharSequence self, Pattern pattern, CharSequence replacement)

​ 说明:字符串替换支持正则匹配,详见 → 正则表达式(Regular Expression)详解

10)字符串反转

Groovy 复制代码
public static String reverse(CharSequence self)

11)大小写转换

Groovy 复制代码
// 转为大写字符串, locale可以传入Locale.ROOT
public String toUpperCase()
public String toUpperCase(Locale locale)
// 转为小写字符串, locale可以传入Locale.ROOT
public String toLowerCase()
public String toLowerCase(Locale locale)

12)数据类型转换

Groovy 复制代码
public static Boolean toBoolean(String self)
public static Integer toInteger(CharSequence self)
public static Long toLong(CharSequence self)
public static Float toFloat(CharSequence self)
public static Double toDouble(CharSequence self)
public static BigInteger toBigInteger(CharSequence self)
public static BigDecimal toBigDecimal(CharSequence self)

2.5.3 字符串匹配

1)、=、==~ 定义

  • ~:创建 Pattern 对象
  • =~:创建 Matcher 对象
  • ==~:匹配字符串

2)、=、==~ 应用

Groovy 复制代码
//等价于: Pattern pattern = Pattern.compile("\\w+")
Pattern pattern = ~ "\\w+" // 通过 ~ 创建Pattern对象
boolean isMatch1 = pattern.matcher("Hello world")
println(isMatch1) // 打印: true

boolean isMatch2 = "Hello World" ==~ "\\w+ \\w+" // 通过 ==~ 匹配字符串
println(isMatch2) // true
boolean isMatch3 = "\\w+ \\w+" ==~ "Hello World" // 通过 ==~ 匹配字符串
println(isMatch3) // false

Matcher matcher = "Hello world" =~ "\\w+" // 通过 =~ 创建Matcher对象
while (matcher.find()) {
    println(matcher.group(0))
}

​ 声明:本文转自【Groovy】变量和基本数据类型

相关推荐
邵皮皮4 个月前
Groovy 入门
groovy
不穿铠甲的穿山甲5 个月前
gradle-tasks.register(‘classesJar‘, Jar)解析
android·java·gradle·groovy
小吴先生6666 个月前
Groovy 规则执行器,加载到缓存
java·开发语言·缓存·groovy
fananchong28 个月前
Jenkinsfile共享库介绍
jenkins·groovy·jenkinsfile·cicd·共享库
慧集通-让软件连接更简单!9 个月前
开发培训-慧集通(iPaaS)集成平台脚本开发Groovy基础培训视频
低代码·api·groovy·ipaas·系统集成·慧集通
命运之手1 年前
【Gradle】Build Multiple Android Variants in Groovy
android·groovy·package·multi-channel·multi-variant
超低空MC1 年前
Android Gradle —— 从 Groovy 快速迁移到 Kotlin DSL
android·java·开发语言·kotlin·gradle·groovy
AskHarries1 年前
Spring Boot集成groovy快速入门Demo
java·spring boot·groovy
s_nshine1 年前
将 build.gradle 配置从 Groovy 迁移到 Kotlin
android·开发语言·kotlin·gradle·groovy·build