Using java-8 now I turned some explicit declaration into a lambda expression and got a compiler error. So suspect it is a "bug" of the current java-8 release (b105).
The sample code defines two Function objects with and without using a lambda expression. Both relay on an Predicate which is used by those functions. While the traditional implementation works, the lambda version reports an error:
java: variable fileExists might not have been initialized
This is not totally wrong, but the predicate is relevant if the Function is used not if the function itself is created (since the explicit version works well). Should I report a bug (someone has a link?) or did I miss something?
public class FileOpener {
public FileOpener(Predicate<File> fileExists) {
this.fileExists = fileExists;
}
final Predicate<File> fileExists;
final Function<File, FileInputStream> openLambda = file -> {
try {
return fileExists.test(file) ? new FileInputStream(file) : null;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
};
// this version compiles
final Function<File, FileInputStream> openFunction = new Function<File, FileInputStream>() {
@Override
public FileInputStream apply(File file) {
try {
return fileExists.test(file) ? new FileInputStream(file) : null;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
};
}
fileExistsinitialized? Aren't the fields initialized prior to the constructor?openLambdais an instance field, therefore, during object creation, it is evaluated PRIOR to the constructor, thusfileExistsis not initialized at that point.