Problem in setting a variable defined in an enclosing scope

65 Views Asked by At

I have one map object named itemClassificationMap that gets its value from readClassificationData() method of ApachePOIExcelUtil class.

Map<String, ItemClassification> itemClassificationMap = new ApachePOIExcelUtil().readClassificationData("dummy");

The readClassificationData() method of ApachePOIExcelUtil class throws exception hence it is to be called within a try catch block.

try {
    Map<String, ItemClassification> itemClassificationMap = new ApachePOIExcelUtil().readClassificationData("dummy");
} catch (Exception e) {
    e.printStackTrace();
}

But this way the map object's scope gets confined to above try catch block hence not accessible later.

If I refactor in following way

Map<String, ItemClassification> itemClassificationMap = null;
try {
    itemClassificationMap = new ApachePOIExcelUtil().readClassificationData("dummy");
} catch (Exception e) {
    e.printStackTrace();
}

compilation fails at the place down the line where it is being accessed inside a lambda expression complaining

Local variable itemClassificationMap defined in an enclosing scope must be final or effectively final

The error becomes

The local variable itemClassificationMap may not have been initialized

if I refactor in following way.

final Map<String, ItemClassification> itemClassificationMap;
try {
    itemClassificationMap = new ApachePOIExcelUtil().readClassificationData("dummy");
} catch (Exception e) {
    e.printStackTrace();
}

Right now I am managing with following solution which is temporary one

Map<String, ItemClassification> itemClassificationMapTemp = null;
try {
    itemClassificationMapTemp = new ApachePOIExcelUtil().readClassificationData("dummy");
} catch (Exception e) {
    e.printStackTrace();
}
Map<String, ItemClassification> itemClassificationMap = itemClassificationMapTemp;

and expecting an even more professional way to handle the scenario. Java experts .. comments please...

1

There are 1 best solutions below

0
On

The variable used inside Lambda needs to be final or effectively final. You can refer here. For your use case, I think you can use your second code and make a duplicate final variable to use it inside Lambda.