I'm doing some tests using lambda expressions but my code does not compile. My lambda implementation is wrong or the exception handling? What would be the correct implementation of the following code?
class MyObject { }
interface Creatable<T> {
T create() throws IOException;
}
/* Using the code: */
Creatable<MyObject> creator = () -> {
try {
return new MyObject();
} catch (IOException e) {
e.printStackTrace();
}
};
MyObject obj1 = creator.create();
If i remove the try catch block and declare the exception to throw in the method, the code compiles and runs normally.
Creatable<MyObject> creator = () -> new MyObject();
The compilation error is:
incompatible types: bad return type in lambda expression