我正在尝试创建一个可以抛出自定义异常的功能界面,我想出的是。
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
@FunctionalInterface
public interface ThrowingFunction<T, R> {
R apply(T t) throws MyException;
}
这对于使用apply函数非常有用,但问题是我还想使用Java函数的andThen功能。当我尝试做类似的事情。
ThrowingFunction<Integer, Integer> times2WithException = (num) -> {
if(num == null) {
throw new MyException("Cannot multiply null by 2");
}
return num * 2;
};
times2WithException.andThen(times2WithException).apply(4);
我收到了错误
Cannot find symbol: method andThen(ThrowingFunction<Integer, Integer>)
有什么我应该使用而不是FunctionalInterface?或者是否需要实现其他功能才能使其与之一起使用?
谢谢!
功能接口仅允许指定一个未实现的功能。但是您可以指定已经具有如下实现的default
函数:
@FunctionalInterface
public interface ThrowingFunction<T, R> {
R apply(T t) throws MyException;
default <U> ThrowingFunction<T, U> andThen(ThrowingFunction<R, U> follow) {
Objects.requireNonNull(follow); // Fail fast
return t -> follow.apply(this.apply(t));
}
}
你期望andThen
方法来自哪里?你没有在任何地方定义它!
@FunctionalInterface
interface ThrowingFunction<T, R> {
R apply(T t) throws MyException;
default <V> ThrowingFunction<T, V> andThen(ThrowingFunction<R, V> after) {
return (T t) -> after.apply(apply(t));
}
}
在这里,您可以利用接口中的default
方法创建andThen
函数。