@FunctionalInterface也实现了并且然后呢?(@FunctionalInterface that also implements andThen?)

编程入门 行业动态 更新时间:2024-10-27 20:29:27
@FunctionalInterface也实现了并且然后呢?(@FunctionalInterface that also implements andThen?)

我试图创建一个可以抛出自定义异常的函数接口,我想到的是。

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)); } }

更多推荐

本文发布于:2023-04-28 09:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实现了   FunctionalInterface   andThen   implements

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!