news 2026/7/21 7:23:47

【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/7/19 16:35:16

永磁同步电机MotorCAD仿真详细流程揭秘

某永磁同步电机motorcad仿真流程,很详细 录制video文档最近在研究永磁同步电机的相关内容&#xff0c;发现MotorCAD这个软件在永磁同步电机仿真方面真的非常强大。今天就来给大家分享一下永磁同步电机MotorCAD的详细仿真流程&#xff0c;同时我还录制了配套的video&#xff0c;…

作者头像 李华
网站建设 2026/7/22 2:10:01

跳出“要么稳要么冲”陷阱:广告预算的确定性与增长性双驱法则

在亚马逊运营中&#xff0c;广告预算分配是一场精密的资源调度艺术&#xff0c;如何在“确保盈利”的确定性与“追求增长”的探索性之间找到平衡&#xff0c;是卖家必须掌握的核心能力。一、锚定底层逻辑&#xff1a;不同生命周期的预算哲学广告预算的设定&#xff0c;必须始于…

作者头像 李华
网站建设 2026/7/18 11:18:08

上海交大造出手机AI助手ColorAgent:不只是工具,更像贴心伙伴

这项突破性研究由上海交通大学与OPPO研究院联合完成&#xff0c;研究成果发表于2025年10月22日的arXiv预印本平台&#xff0c;论文编号为arXiv:2510.19386v1。研究团队由来自上海交通大学的李宁、吴正、张伟明等多位学者&#xff0c;以及OPPO研究院的林旗强、莫晓芸、赵音等专家…

作者头像 李华
网站建设 2026/7/22 3:00:59

机器视觉介绍

机器视觉的定义机器视觉&#xff08;Machine Vision&#xff09;是指通过计算机和图像处理技术模拟人类视觉功能&#xff0c;实现对物体识别、测量、定位和分析的自动化系统。广泛应用于工业检测、自动驾驶、医疗影像等领域。机器视觉的核心技术图像采集 通过摄像头、工业相机或…

作者头像 李华
网站建设 2026/7/20 10:39:16

基于鲹鱼优化算法(GTO)优化Canopy聚类附matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。 &#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知,完整Matlab代码获取及仿…

作者头像 李华
网站建设 2026/7/19 17:20:10

IMU和GPS ekf融合定位 从matlab到c++代码实现 基于位姿状态方程

IMU和GPS ekf融合定位 从matlab到c代码实现 基于位姿状态方程&#xff0c;松耦合 文档且详细 蹲在实验室捯饬了三天咖啡机之后&#xff0c;我终于把IMU和GPS的EKF融合算法从Matlab搬到了C。这事儿就像把乐高积木从说明书模式切换到自由创作模式——你知道原理是对的&#xff0…

作者头像 李华