1

I am building a chess game application with javafx and I'm encountering a problem that I don't quite understand. I am trying to implement mouse click events for my chess pieces, but when I try to do so for each piece using a for loop I get the error "local variables referenced from a lambda expression must be final or effectively final". However when I create each mouse event independently there's no problem.

public static ChessPiece[] BlackPieces = {
    new ChessPieceRook("BLACK"),
    new ChessPieceKnight("BLACK"),
    new ChessPieceBishop("BLACK"),
    new ChessPieceQueen("BLACK"),
    new ChessPieceKing("BLACK"),
    new ChessPieceBishop("BLACK"),
    new ChessPieceKnight("BLACK"),
    new ChessPieceRook("BLACK")};

this works:

BlackPieces[0].setOnMouseClicked((MouseEvent event) -> {
    if (turn % 2 == 0) {
        setSelection(BlackPieces[0]);
        setSelectionClip(PieceClips[0]);
    }
});

but this doesn't:

for (int i = 0; i < 8; i++) {
    BlackPieces[i].setOnMouseClicked((MouseEvent event) -> {
        if (turn % 2 == 0) {
            setSelection(BlackPieces[i]);
            setSelectionClip(PieceClips[i]);
        }
    });
}

can anyone explain this to me?

  • What does "it doesn't work" mean? – James_D Jan 19 '16 at 15:27
  • The value of `i` is changing after you define the functions. – Mad Physicist Jan 19 '16 at 15:29
  • Oh I see what you mean. I'm having trouble getting used to these lambda expressions, thanks for the insight! – user5811159 Jan 19 '16 at 15:36
  • Possible duplicate of [local variables referenced from a lambda expression must be final or effectively final](http://stackoverflow.com/questions/27592379/local-variables-referenced-from-a-lambda-expression-must-be-final-or-effectively) – James_D Jan 19 '16 at 15:55

0 Answers0