Does Groovy @Canonical work with private fields?

I keep getting a "Could not find matching constructor" when I use @Canonical annotation with private fields. May I know how I can get the following code to compile and pass the asserts? Thanks :)

@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

Regards, John

Answers


Yes, you can do that.

@Canonical is a shorthand for @TupleConstructor @ToString and @EqualsAndHashCode annotations with default values. [code] You can specify them by hand, or simply add necessary annotation before Canonical. @TupleConstructor allows you to set fields, via includeFields or include annotation fields. [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

Need Your Help

Analyze log files from many languages using a single tool. And recommendations of logging frameworks

c# php c++ logging

We have a system build on lots of languages. The ones we are interested in logging, in order of priority, are:

Dynamic table with data from infobox data on other pages in a MediaWiki

mysql mediawiki dynamic-pages semantic-mediawiki

We're using mediawiki at our office and we needed to create infoboxes to store informations about softwares that we manage.