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"