2014-01-10 40 views
9

Groovy的飛船運營商<=>提供了一種實現比較的簡單方法。我怎樣才能以更小的方式鏈接它,然後下面的代碼?在這個例子中,如果價格相同,我想先按價格比較價格,然後按名稱比較價格。如何鏈接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 
    } 
} 

回答

18

由於飛船操作<=>返回0,如果兩者相等和0根據Groovy的事實是假的,你可以使用Elvis操作符?:有效鏈中的排序標準。


class Item implements Comparable { 
    int price 
    String name 

    int compareTo(Item other) { 
    price <=> other.price ?: name <=> other.name 
    } 
} 
相關問題