[英]Java failed to compile Functional Interface with generic parameter and default method implementation
I'm trying to extend this interface:我正在尝试扩展此接口:
@FunctionalInterface
public interface HandlerFunction<T extends ServerResponse> {
Mono<T> handle(ServerRequest request);
}
Like this:像这样:
@FunctionalInterface
public interface HandlerFn<R extends ServerRequest> extends HandlerFunction<ServerResponse> {
default Mono<ServerResponse> handle(ServerRequest request) {
return handleFn(request);
}
Mono<ServerResponse> handleFn(R request);
}
I'm getting this error (on handleFn(request)
):我收到此错误(在handleFn(request)
上):
The method handleFn(R) in the type HandlerFn<R> is not applicable for the arguments (ServerRequest)
In this code snippet, why when calling handleFn(request)
the type R
is not inferred as ServerRequest
?在此代码片段中,为什么在调用handleFn(request)
时类型R
不会被推断为ServerRequest
?
request
is a ServerRequest
, not an R
. request
是一个ServerRequest
,而不是一个R
。 R
could be ServerRequest
, but it could be any other subclass of it. R
可以是ServerRequest
,但也可以是它的任何其他子类。
R
is declared on the class, not the method. R
是在 class 上声明的,而不是方法上。 The type of R
is determined at the declaration of the reference to the HandlerFn
, not at the call site of the handleFn
method. R 的类型是在声明对R
的引用时确定的,而不是在HandlerFn
方法的调用handleFn
。
You could cast inside the default method:您可以在默认方法中进行转换:
return handleFn((R) request);
which is an unchecked cast (at that point; it would be checked elsewhere).这是一个未经检查的演员表(那时;它将在其他地方检查)。
If you declared the method as a generic method, it would work in handle
:如果您将该方法声明为泛型方法,它将在handle
中工作:
<RR extends ServerRequest> Mono<ServerResponse> handleFn(RR request);
(You wouldn't then need R
on the interface. I just called it RR
to emphasize that it is a separate type variable). (然后你就不需要接口上的R
。我只是称它为RR
以强调它是一个单独的类型变量)。
But, in fact, there is no point in such a type variable: this gives no advantage over declaring the method non-generically:但是,事实上,这样的类型变量没有任何意义:与非泛型声明方法相比,这没有任何优势:
Mono<ServerResponse> handleFn(ServerRequest request);
which, of course, has no advantage over the handle
method.当然,这与handle
方法相比没有优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.