Kotlin 和通用 Return 类型与 Springs ResponseEntity
Kotlin and Generic Return Type with Springs ResponseEntity
假设我在 Spring 中有一个使用 Kotlin 的控制器方法,我想 return ResponseEntity<Test>
或 ResponseEntity<Error>
。
如何在 Kotlin 中完成这项工作?我尝试输入 ResponseEntitiy<Any>
或 ResponseEntity<*>
但 Kotlin 总是抱怨。
那么如何使 return 类型真正通用?
@GetMapping
fun test(): Mono<ResponseEntity<?????>>
{
return Mono.just(1)
.map { ResponseEntity.ok(Test("OK") }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body(Error("Error"))))
}
您还需要更改正文以便为每次调用提供正确的类型:
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<*>))
}
或者,
fun test(): Mono<ResponseEntity<Any>> {
return Mono.just(1)
.map { ResponseEntity.ok<Any>(Test("OK")) }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body<Any>(Error("Error"))))
}
如果 ResponseEntity
是用 Kotlin 编写的,它可能是协变的并简化了 Any
的情况,但事实并非如此。
(注意:我目前无法测试,所以这些可能需要一些修复)
假设我在 Spring 中有一个使用 Kotlin 的控制器方法,我想 return ResponseEntity<Test>
或 ResponseEntity<Error>
。
如何在 Kotlin 中完成这项工作?我尝试输入 ResponseEntitiy<Any>
或 ResponseEntity<*>
但 Kotlin 总是抱怨。
那么如何使 return 类型真正通用?
@GetMapping
fun test(): Mono<ResponseEntity<?????>>
{
return Mono.just(1)
.map { ResponseEntity.ok(Test("OK") }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body(Error("Error"))))
}
您还需要更改正文以便为每次调用提供正确的类型:
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<*>))
}
或者,
fun test(): Mono<ResponseEntity<Any>> {
return Mono.just(1)
.map { ResponseEntity.ok<Any>(Test("OK")) }
.switchIfEmpty(Mono.just(ResponseEntity.badRequest().body<Any>(Error("Error"))))
}
如果 ResponseEntity
是用 Kotlin 编写的,它可能是协变的并简化了 Any
的情况,但事实并非如此。
(注意:我目前无法测试,所以这些可能需要一些修复)