94. LVTI can be final and effectively final

As a quick reminder, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.

The following snippet of code represents the use case of an effectively final variable (trying to reassign the ratio variable will result in an error, which means that this variable is effectively final) and two final variables (trying to reassign the limit and bmi variables will result in an error, which means that these variables are final):

public interface Weighter {
float getMarginOfError();
}

float ratio = fetchRatio(); // this is effectively final

var weighter = new Weighter() {
@Override
public float getMarginOfError() {
return ratio * ...;
}
};

ratio = fetchRatio(); // this reassignment will cause error

public float fetchRatio() {

final float limit = new Random().nextFloat(); // this is final
final float bmi = 0.00023f; // this is final

limit = 0.002f; // this reassignment will cause error
bmi = 0.25f; // this reassignment will cause error

return limit * bmi / 100.12f;
}

Now, let's replace the explicit types with var. The compiler will infer the correct types for these variables (ratio, limit, and bmi) and maintain their state—ratio will be effectively final while limit and bmi are final. Trying to reassign any of them will cause a specific error:

var ratio = fetchRatio(); // this is effectively final

var weighter = new Weighter() {
@Override
public float getMarginOfError() {
return ratio * ...;
}
};

ratio = fetchRatio(); // this reassignment will cause error

public float fetchRatio() {

final var limit = new Random().nextFloat(); // this is final
final var bmi = 0.00023f; // this is final

limit = 0.002f; // this reassignment will cause error
bmi = 0.25f; // this reassignment will cause error

return limit * bmi / 100.12f;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.235.144