当我在私有字段中使用@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
此致 约翰
答案 0 :(得分:3)
是的,你可以这样做。
@Canonical
是带有默认值的@TupleConstructor
@ToString
和@EqualsAndHashCode
注释的简写。 [code]您可以手动指定它们,或者只需在 Canonical
之前添加必要的注释。 @TupleConstructor
允许您通过includeFields
或include
注释字段设置字段。 [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