There is the following code:

String[] prop_run; prop_run[0] = "classA"; prop_run[1] = "classB"; for (int i = 0; i <= prop_run.length; i++) { new Thread(() -> RunClassByName(prop_run[i])).start(); } private static void RunClassByName(String class_name) { //... } return; 

Result:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Local variable i defined in an enclosing scope must be final or effectively final at Main.main(Main.java:24) 

On the 24th line, the following is written: new Thread(() -> myFunction(prop_run[i])).start();

How to fix the problem?

    1 answer 1

    So try it. A final variable is required to pass to an anonymous class that will make a lambda. It seems to work.

     for (int i = 1; i <= prop_run.length; i++) { final int j = i; new Thread(() -> myFunction(prop_run[j])).start(); } 
    • Yes, it seems to work, then something is wrong with the old question: D - nick
    • more precisely the answer to the question - nick
    • It is better to make a string (method parameter) final, since this Or immediately a class that implements Runnable, which will take this line in the constructor - zRrr
    • @zRrr offer your option. I'm not strong in lambdas, I don’t know exactly how they work at all and with final ones in particular. - Sergey
    • @Lesperanza That's it. The variable must be declared final or be effectively final (i.e., not actually changed, true for Java 8 and higher). Teach materiel. - a_gura