我正在尝试创建一个可以抛出自定义异常的函数式接口(interface),我的想法是。
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?还是我需要实现另一个函数才能使其与 andThen 一起使用?
谢谢!
最佳答案
函数式接口(interface)只允许指定一个未实现的函数。但是您可以指定已经具有如下实现的 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));
}
}
关于java - @FunctionalInterface 也实现了andThen?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100034/