Groovy @Canonical是否与私有领域合作?

时间:2014-02-01 14:57:16

标签: groovy

当我在私有字段中使用@Canonical批注时,我不断收到“找不到匹配的构造函数”。我可以知道如何获得以下代码来编译并传递断言吗?谢谢:))

@groovy.transform.Canonical(includes = ['x','y'])
@groovy.transform.EqualsAndHashCode(includeFields = true)
class Cell implements Comparable<Cell>{
    private int x
    private int y

    int compareTo(Cell cell){
        x <=> cell.x ?: y <=> cell.y ?: 0
    }
}

Cell cell = new Cell(1,0);
Cell sameCell = new Cell(1,0);
def setOfLiveCells = [] as Set

assert setOfLiveCells.add(cell) // cell is added
assert cell == sameCell // cell equals
assert ! setOfLiveCells.add(sameCell) //should not assert

此致 约翰

1 个答案:

答案 0 :(得分:3)

是的,你可以这样做。

@Canonical是带有默认值的@TupleConstructor @ToString@EqualsAndHashCode注释的简写。 [code]您可以手动指定它们,或者只需在 Canonical之前添加必要的注释@TupleConstructor允许您通过includeFieldsinclude注释字段设置字段。 [doc]

@groovy.transform.TupleConstructor(includeFields = true)
@groovy.transform.Canonical
class Cell implements Comparable<Cell>{
    private int x
    private int y

    int compareTo(Cell cell){
        x <=> cell.x ?: y <=> cell.y ?: 0
    }
}

Cell cell = new Cell(1,0);
Cell sameCell = new Cell(1,0);
def setOfLiveCells = [] as Set

assert setOfLiveCells.add(cell) // cell is added
assert cell == sameCell // cell equals
assert ! setOfLiveCells.add(sameCell) //should not assert