Java可选:映射到子类或其他超类

vas*_*orc 0 java scala optional akka akka-http

我正在尝试用Manning的Manning的“ Akka in Action”重写一个POC项目的scala示例。该项目是用于创建事件和购买票证的小型Http服务器。

我正在演员可以发送影片Optional<Event>给我的时刻RestApi。根据是否存在该值,我应该使用OKelse 完成调用NOT_FOUND

在Scala中,代码段如下所示:

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

... where 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));
    }
Run Code Online (Sandbox Code Playgroud)

无法编译:Bad return type in lambda expression: Route cannot be converted to RouteAdapter。较长的(第一个)complete返回a RouteAdapter,第二个返回a Route。如果我这样重写上面的函数:

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

...然后编译器不会抱怨,但是映射Optional并不是正确的方法。

Java没有foldOptional的方法(至少在SE8中没有),该方法允许首先传递fallback-to值。

我很好奇是否可以尊重功能风格来编写此功能。

更新

如评论中所问,这些是complete来自akka-httpjavadsl库的方法的签名:

  def complete(status: StatusCode): Route = RouteAdapter(
    D.complete(status.asScala))
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lov 5

什么是退货类型complete(OK, maybeEvent.get(), Jackson.marshaller())

我认为RouteAdapter。如果是的话将它转换为Route使链将被绑定到Route没有RouteAdaper,并在年底会不会有麻烦与超类转换为子类。