So I've started playing with Java 8 streams/lambda expressions and have encountered and interesting issue that I'm not really sure how to resolve. So here I am, asking you for help.
Sample code in question:
public void insertBlankPages(File inputFile, String outputFile, final int OFFSET) {
PDDocument newDocument;
PDDocument oldDocument;
try {
newDocument = createNewDocument();
oldDocument = createOldDocument(inputFile);
List<PDPage> oldPages = getAllPages(oldDocument);
oldPages.stream()
.limit(oldPages.size() - OFFSET)
.forEach(page -> {
newDocument.addPage(page);
newDocument.addPage(new PDPage(page.getMediaBox()));
});
newDocument.save(outputFile);
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
} finally {
newDocument.close();
oldDocument.close();
}
}
With the code above, compiler complains about the call to close() in the finally block. The error is: "Variable newDocument might not have been initialized". Same for oldDocument.
Naturally, I go ahead and initialize the variables as follow:
PDDocument newDocument = null;
PDDocument oldDocument = null;
Now I get compiler error "Variable used in lambda expression should be effectively final".
How to go about this?
Methods createNewDocument and createOldDocument throw an exception, so the calls must be within try/catch block. I also need to close the documents within the finally block.
I should be able to work around this issue by using try-with-resources. But, I'm curious to hear if there's any other proper solution for this.
Thanks.