Groovyは、Javaでのコンパイルエラーを回避しているようです。
Main.java:2: illegal forward reference
North(South), South(North), East(West), West(East), Up(Down), Down(Up);
^
Main.java:2: illegal forward reference
North(South), South(North), East(West), West(East), Up(Down), Down(Up);
^
Main.java:2: illegal forward reference
North(South), South(North), East(West), West(East), Up(Down), Down(Up);
^
3 errors
groovyコンパイラはそれについて文句を言いませんが、前方宣言を必要とする列挙値を次のように初期化しますnull
。
public enum Direction {
North(South), South(North), East(West), West(East), Up(Down), Down(Up)
Direction(Direction d){
println "opposite of $this is $d"
}
}
Direction.South // Force enum instantiation in GroovyConsole.
出力:
opposite of North is null
opposite of South is North
opposite of East is null
opposite of West is East
opposite of Up is null
opposite of Down is Up
Javaでうまく機能しているように見える1つの解決策は、値を初期化するためにクラスにブロックを追加することstatic
Direction
opposite
です。Groovyに翻訳すると、次のようになります。
enum Direction {
North, South, East, West, Up, Down
private Direction opposite
Direction getOpposite() { opposite }
static {
def opposites = { d1, d2 -> d1.opposite = d2; d2.opposite = d1 }
opposites(North, South)
opposites(East, West)
opposites(Up, Down)
}
}
Direction.values().each {
println "opposite of $it is $it.opposite"
}
これで正しい値が出力されます:
opposite of North is South
opposite of South is North
opposite of East is West
opposite of West is East
opposite of Up is Down
opposite of Down is Up
アップデート
別の、おそらくもっと簡単な解決策は、列挙型の方向インデックスを使用して反対を見つけることができます。
public enum Direction {
North(1), South(0), East(3), West(2), Up(5), Down(4)
private oppositeIndex
Direction getOpposite() {
values()[oppositeIndex]
}
Direction(oppositeIndex) {
this.oppositeIndex = oppositeIndex
}
}
しかし、最初の1つは、インデックスheheにこれらの魔法数を必要としないため、より明確になります。
アップデート2
さて、私はおそらくここでゴルフ場に少し入り込んでいますが、列挙値(それらのインデックス)を使用するだけで、余分なフィールドを必要とせずに反対方向に進むことができます:ordinal()
enum Direction {
North, South, East, West, Up, Down
Direction getOpposite() {
values()[ordinal() + ordinal() % 2 * -2 + 1]
}
}
見た目ほど怖くない!偶数の方向(北、東、上)ordinal() + 1
は反対の方向を返しますが、奇数の方向(他の方向)はでの方向を返しordinal() - 1
ます。もちろん、列挙型の要素の順序に大きく依存していますが、簡潔さが好きではありませんか?= D