我试图创建一个可以抛出自定义异常的函数接口,我想到的是。
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函数的Then函数。 当我尝试做类似的事情时。
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? 还是有另一个功能,我需要实现它来与它合作,然后呢?
谢谢!
I'm trying to create a functional interface that can throw an custom exception, what I've come up with is.
public class MyException extends Exception { public MyException(String message) { super(message); } } @FunctionalInterface public interface ThrowingFunction<T, R> { R apply(T t) throws MyException; }This works great for using the apply function but the problem is I'd also like to use the andThen capabilities of Java's functions. When I try to do something like.
ThrowingFunction<Integer, Integer> times2WithException = (num) -> { if(num == null) { throw new MyException("Cannot multiply null by 2"); } return num * 2; }; times2WithException.andThen(times2WithException).apply(4);I get the error
Cannot find symbol: method andThen(ThrowingFunction<Integer, Integer>)Is there something I should use instead of FunctionalInterface? Or is there another function I need to implement to get it to work with andThen?
Thanks!
最满意答案
功能接口只允许指定一个未实现的功能。 但是你可以指定已经有这样的实现的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)); } }Functional interfaces are only allowed to specify one unimplemented function. But you can specify default functions that already have an implementation like this:
@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)); } }更多推荐
发布评论