java可选:Map到子类或超类

pcrecxhr  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(218)

我试图用java重新编写manning的“akka in action”中的一个poc项目的scala示例。该项目是一个用于创建事件和购买票证的小型http服务器。
我正处在一个演员可以发广告的时刻 Optional<Event> 给我的 RestApi . 根据值是否存在,我应该用 OK ,否则 NOT_FOUND .
在scala中,代码段如下所示:

get {
          // GET /events/:event
          onSuccess(getEvent(event)) {
            _.fold(complete(NotFound))(e => complete(OK, e))
          }
        }

…在哪里 getEvent 返回一个 Option[Event] (相当于java的 Optional<Event> ). 我就是这样用java重写的:

get(() -> onSuccess(() -> getEvent(event), eventGetRoute()))

   ...
    //and eventGetRoute() is a function:
    private Function<Optional<Event>, Route> eventGetRoute() {
        return maybeEvent -> maybeEvent.map(event -> complete(OK, event, Jackson.marshaller())).orElseGet(() -> complete(NOT_FOUND));
    }

这不会编译: Bad return type in lambda expression: Route cannot be converted to RouteAdapter . 越长(第一个) complete 返回一个 RouteAdapter 第二个返回 Route . 如果我像这样重新编写上述函数:

private Function<Optional<Event>, Route> eventGetRoute() {
    return maybeEvent -> {
        if(maybeEvent.isPresent()) {
            return complete(OK, maybeEvent.get(), Jackson.marshaller());
        }
        return complete(NOT_FOUND);
    };
}

…然后编译器不会抱怨,但是Map可选的。
java没有 fold 方法(至少不在se8中),它允许首先将回退传递给值。
我很好奇是否有可能用尊重函数的风格来写这个函数。
更新:
如评论中所问,这些是 complete 方法来自 akka-http javadsl库:

def complete(status: StatusCode): Route = RouteAdapter(
    D.complete(status.asScala))

def complete[T](status: StatusCode, value: T, marshaller: Marshaller[T, RequestEntity]) = RouteAdapter {
    D.complete(ToResponseMarshallable(value)(fromToEntityMarshaller(status.asScala)(marshaller)))
  }
sigwle7e

sigwle7e1#

什么是退货类型 complete(OK, maybeEvent.get(), Jackson.marshaller()) ?
我想 RouteAdapter . 如果是这样的话 Route 所以链子会绑在 Route 不是 RouteAdaper 最后将不会有麻烦从超类到子类的转换。

相关问题