Leo*_*ngs 10 groovy chaining spaceship-operator
Groovy拥有太空船操作员<=>,提供了一种简单的方法来实现比较.我怎样才能以更加时髦的方式将其链接到下面的代码?在这个例子中,我想首先按价格比较项目,然后按名称比较两个具有相同价格的项目.
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
}
}
Run Code Online (Sandbox Code Playgroud)
Leo*_*ngs 23
由于<=>根据Groovy Truth,如果两者相等且0为假,则宇宙飞船运营商返回0,您可以使用elvis运算符?:有效地链接排序标准.
class Item implements Comparable {
int price
String name
int compareTo(Item other) {
price <=> other.price ?: name <=> other.name
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |