如何链接groovy';s宇宙飞船操作员用于多级分拣?
Groovy具有spaceship操作符如何链接groovy';s宇宙飞船操作员用于多级分拣?,groovy,chaining,spaceship-operator,Groovy,Chaining,Spaceship Operator,Groovy具有spaceship操作符,它提供了一种实现比较的简单方法。如何以比下面的代码更为Groove的方式链接它?在这个例子中,我想先比较价格,然后比较名称,如果两者的价格相同 class Item implements Comparable { int price String name int compareTo(Item other) { int result = price <=> other.price if (result == 0) {
,它提供了一种实现比较的简单方法。如何以比下面的代码更为Groove的方式链接它?在这个例子中,我想先比较价格,然后比较名称,如果两者的价格相同
class Item implements Comparable {
int price
String name
int compareTo(Item other) {
int result = price <=> other.price
if (result == 0) {
result = name <=> other.name
}
return result
}
}
类项实现了可比较的{
整数价格
字符串名
int比较(项目其他){
int结果=价格其他价格
如果(结果==0){
结果=name other.name
}
返回结果
}
}
根据Groovy Truth,由于spaceship操作符
返回0,如果两者相等且0为false,则可以使用elvis操作符?:
有效地链接排序标准
class Item implements Comparable {
int price
String name
int compareTo(Item other) {
price <=> other.price ?: name <=> other.name
}
}
类项实现了可比较的{
整数价格
字符串名
int比较(项目其他){
price other.price?:name other.name
}
}