groovy学习笔记(04)- 操作符
操作符
概念
Groovy中操作符实际都是方法,支持操作符的重载
相等
遵循最小意外原则,Groovy中==等于Java中的equals()方法
要检查是否对象相等,需使用is()函数
Integer x = new Integer(2)
Integer y = new Integer(2)
Integer z
println x == y //true
println x.is(y) //false
println z == null //true
println z.is(null) //true
重载的操作符
assert 4 + 3 == 7 //4.plus(3)
assert 4 - 3 == 1 //4.minus(3)
assert 4**3 == 64 //4.power(3)
assert 4 / 3 == 1.3333333333 //4.div(3)
assert 4.intdiv(3) == 1 //整除
assert 4 > 3 //4.compareTo(3)
assert 4 <=> 3 == 1 //4.compareTo(3)
安全引用操作符
?.表示如果对象为空,则什么都不做
//old
List<Person> people = [null, new Person(name: "Jack")]
for (Person person : people) {
if (person != null) {
println person.name
}
}
//output
//Jack
println()
//new
for (Person person : people) {
println person?.name
}
//output 仍然会被输出,仅表示为 null 时不调用.name
//null
//Jack
猫王操作符
Groovy会将三元操作符的操作数强制转为boolean
?:是三元操作符的简写方式
Java 方式
String agentStatus = "Active"
String status = agentStatus != null ? agentStatus : "Inactive"
assert status == "Active"
Groovy 方式
status = agentStatus ? agentStatus : "Inactive"
assert status == "Active"
简写
status = agentStatus ?: "Inactive"
assert status == "Active"

浙公网安备 33010602011771号