MrRizk MrRizk - 12 days ago 6
Java Question

generate 30 lambda expression using for loop

I want to create event set on mouse click for 30 objects all of them do the same:

for(int i=0;i<30;i++){
seats[i].setOnMouseClicked(e->{
seats[i].setEffect(lighting);
});
}


But I keep getting these error:

error: local variables referenced from a lambda expression must be final or effectively final
seats[i].setEffect(lighting);


Any suggestion how to fix it instead of writing it manually 30 times

Answer

You cannot reference the variable i inside the lambda expression, as its value will have changed when the lambda is executed. Instead, do:

for(int i=0;i<30;i++){
    Node seat = seats[i];
    seat.setOnMouseClicked(e->{
        seat.setEffect(lighting);       
    });
}

This assumes lighting is either explicitly final (i.e. declared as final), "effectively final" (i.e. is only assigned a value once, so could be declared final without introducing a compile error), or is a field (not a local variable).