local variables referenced from a lambda expression must be final or effectively final

前端 未结 3 403
情深已故
情深已故 2020-12-10 11:10

I have a JavaFX 8 program (for JavaFXPorts cross platfrom) pretty much framed to do what I want but came up one step short. The program reads a text file, counts the lines

3条回答
  •  借酒劲吻你
    2020-12-10 11:23

    The error you encountered means that every variable that you access inside a lambda expressions body has to be final or effectively final. For the difference, see this answer here: Difference between final and effectively final

    The problem in your code is the following variable

    String readln2 = null;
    

    The variable gets declared and assigned later on, the compiler can not detect if it gets assigned once or multiple times, so it is not effectively final.

    The easiest way to solve this is to use a wrapper object, in this case a StringProperty instead of a String. This wrapper gets assigned only once and thus is effectively final:

    StringProperty readln2 = new SimpleStringProperty();
    readln2.set(in.readLine());
    button.setOnAction(e -> l.setText(readln2.get()));
    

    I shortened the code to show only the relevant parts..

提交回复
热议问题