news 2026/3/1 15:05:30

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【Groovy】变量和基本数据类型

1 变量

​ 1)变量的声明

int a = 1

def b

def c = 1

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

a = 1

b = "abc"

​ 2)变量命名规范

变量名可以由字母、数字、下划线(_)和美元符号($)组成,但是不能以数字开头,且大小写敏感。

不能有空格、@、#、+、-、/ 等符号。

应该使用有意义的名称,达到见名知意的目的,最好以小写字母开头。

不能与 Groovy 语言的关键字或是基本数据类型重名。

​ 3)可变类型变量

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

def a = new Object()

a = 1

a = 1f

a = "xyz"

a = new StringBuffer()

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

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 的使用方法一样,如下。

BigInteger a = null

def b = null

void fun1() {

/***/

}

Object fun2() {

return null

}

2.1.2 安全访问符(?.)

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

String a = "abc"

println(a?.substring(1)) // 打印: bc

String b = null

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

2.1.3 Elvis 运算符(?:)

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

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)整数的进制表示

// 二进制(以0b开头)

def a = 0b101

// 八进制(以0开头)

def a = 0765

// 十六进制(以0x开头)

def a = 0x8af

​ 3)数字分割

def a = 1_23_456_7

def b = 1.23_456_7

def c = 0xFF_FF_FF

​ 4)times

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)浮点数科学计数法

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 转义字符

\t —— Tab制表符

\b —— 退格

\n —— 换行(LF)

\r —— 回车(CR)

\' —— 单引号

\" —— 双引号

\\ —— 反斜杠

\$ —— 美元符号

2.5 字符串类型

2.5.1 字符串的定义

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

String str1 = 'abc'

def str2 = "efg"

def str3 = '''first

second'''

def str4 = """第一行

第二行"""

def str5 =/123

456/

// 字符串插值

def count = 15

def str5 = "买了${count}个苹果" // 买了15个苹果

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

单引号和三引号不支持插值、转义字符(' 和 \ 除外)、混合编程;双引号、三双引号和斜线支持插值、转义字符、混合编程。

单引号和双引号不支持多行字符串;三引号、三双引号和斜线支持多行字符串(保留字符串中的换行和缩进)。

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

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)判空

// 字符串长度是否为0 (length == 0)

public boolean isEmpty()

// 字符串中是否只存在空字符 (indexOfNonWhitespace() == length)

public boolean isBlank()

​ 2)去掉首尾空字符

public String trim()

​ 3)查找字符

public static String find(CharSequence self, CharSequence regex)

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

​ 4)查找字符索引

// 从前往后查找索引

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)统计字符个数

// 统计self中text子串的个数

public static int count(CharSequence self, CharSequence text)

​ 6)字符串匹配

// 判断字符串是否以prefix开头

public boolean startsWith(String prefix)

public boolean startsWith(String prefix, int toffset)

// 判断字符串是否以suffix结尾

public boolean endsWith(String suffix)

​ 7)获取子串

public String substring(int beginIndex)

public String substring(int beginIndex, int endIndex)

public CharSequence subSequence(int beginIndex, int endIndex)

​ 8)字符串分割

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)字串替换

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)字符串反转

public static String reverse(CharSequence self)

​ 11)大小写转换

// 转为大写字符串, locale可以传入Locale.ROOT

public String toUpperCase()

public String toUpperCase(Locale locale)

// 转为小写字符串, locale可以传入Locale.ROOT

public String toLowerCase()

public String toLowerCase(Locale locale)

​ 12)数据类型转换

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)、=、==~ 应用

//等价于: 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))

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/1 18:51:50

端到端自动驾驶仿真新范式:aiSim如何解决智驾测试的“灾难性挑战“

1 引言&#xff1a;从模块化到端到端的智驾革命随着智能驾驶技术快速发展&#xff0c;端到端解决方案正成为行业新趋势。与传统规则驱动的模块化方案相比&#xff0c;学习驱动的端到端方案具备更强的泛化能力、全面优化优势和持续学习能力。然而&#xff0c;这种变革对仿真测试…

作者头像 李华
网站建设 2026/2/26 11:27:29

【优化】避免繁琐设置字符编码,简单C/C++中文处理方法

字符串字面量在C/C中的中文处理 一、字符串字面量的本质 在C/C中&#xff0c;字符串字面量是存储在静态内存区域的字符数组。其基本形式为&#xff1a; const char* str "中文字符";但直接使用窄字符&#xff08;char&#xff09;处理中文时&#xff0c;常因编码问题…

作者头像 李华
网站建设 2026/2/13 14:15:16

牛客周赛 Round 111

设一个数组 &#xfffd; { 2 , 3 , 4 , 3 , 5 , 1 } b{2,3,4,3,5,1}&#xff0c;则 &#xfffd; ( &#xfffd; ) 2 3 4 5 14 L(b)234514&#xff0c; &#xfffd; ( &#xfffd; ) 1 5 6 R(b)156。 小芳希望小红构造一个长为 &#xfffd; …

作者头像 李华
网站建设 2026/2/27 17:13:32

定性与定量考核的结合

在现代企业管理中&#xff0c;如何科学、公正地评估员工绩效&#xff0c;始终是一个核心议题。要实现全面而准确的评估&#xff0c;关键在于将定量考核的客观性与定性考核的深刻性有效结合。 单纯的定量考核&#xff08;“计件”&#xff09;提供了“做什么”的客观数据&#x…

作者头像 李华
网站建设 2026/2/23 19:21:20

如何衡量团队产出效率

在现代组织中&#xff0c;团队的产出效率直接决定企业的竞争力与执行力。**要科学衡量团队产出效率&#xff0c;核心在于建立多维度的指标体系&#xff0c;将成果、过程与协作因素综合评估&#xff0c;以实现对绩效的量化与优化。**单纯用“工作量”或“加班时间”衡量团队贡献…

作者头像 李华
网站建设 2026/2/24 7:38:37

使用格子玻尔兹曼方法(LBM)模拟热扩散的Matlab代码

使用格子玻尔兹曼方法&#xff08;LBM&#xff09;模拟热扩散&#xff0c;Matlab代码格子玻尔兹曼方法&#xff08;LBM&#xff09;搞热扩散模拟其实挺有意思的&#xff0c;今天咱们用Matlab整一个简单的二维版本。先上核心思路&#xff1a;把温度场当作被动标量&#xff0c;用…

作者头像 李华