Dac*_*ein 7 kotlin spring-webflux
假设我在 Spring 中有一个使用 Kotlin 的控制器方法,并且我想返回 aResponseEntity<Test>或ResponseEntity<Error>。
我怎样才能在 Kotlin 中实现这个功能?我尝试过使用ResponseEntitiy<Any>orResponseEntity<*>但 Kotlin 总是抱怨。
那么如何让返回类型真正通用呢?
@GetMapping
fun test(): Mono<ResponseEntity<?????>>
{
return Mono.just(1)
.map { ResponseEntity.ok(Test("OK") }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body(Error("Error"))))
}
Run Code Online (Sandbox Code Playgroud)
您还需要更改正文,以便为每个调用提供正确的类型:
fun test(): Mono<ResponseEntity<*>> {
return Mono.just(1)
.map { ResponseEntity.ok(Test("OK")) as ResponseEntity<*> }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body(Error("Error")) as ResponseEntity<*>))
}
Run Code Online (Sandbox Code Playgroud)
交替,
fun test(): Mono<ResponseEntity<Any>> {
return Mono.just(1)
.map { ResponseEntity.ok<Any>(Test("OK")) }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body<Any>(Error("Error"))))
}
Run Code Online (Sandbox Code Playgroud)
如果ResponseEntity是用 Kotlin 编写的,它可能是协变的并简化了Any情况,但事实并非如此。
(注意:我目前无法测试,因此可能需要一些修复)
| 归档时间: |
|
| 查看次数: |
9490 次 |
| 最近记录: |