In which cases can we replace an anonymous class with a lambda expression? All interfaces are from the standard java class library.
a)
final double variable = 10;
Serializable serializable = new Serializable() {
double applyFun(double x) {
return x + variable;
}
};
Note, the
Serializable is a standard marker interface that doesn't contain any methods.b)
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(100);
return "hello";
}
};
c)
Future<Double> future = new Future<Double>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public Double get() throws InterruptedException, ExecutionException {
return null;
}
// and other methods...
};
d)
// see NIO.2
PathMatcher matcher = new PathMatcher() {
@Override
public boolean matches(Path path) {
return false;
}
};
To solve this problem, it is recommended to try it in code or think well.