groovy学习笔记(04)- 操做符

操做符

概念

Groovy中操做符实际都是方法,支持操做符的重载java

相等

遵循最小意外原则,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
==?:==是三元操做符的简写方式code

Java 方式对象

String agentStatus = "Active"
String status = agentStatus != null ? agentStatus : "Inactive"
assert status == "Active"

Groovy 方式class

status = agentStatus ? agentStatus : "Inactive"
assert status == "Active"

简写List

status = agentStatus ?: "Inactive"
assert status == "Active"
相关文章
相关标签/搜索