具有Springs ResponseEntity的Kotlin和通用返回类型

达赫施泰因

可以说我在Spring中使用Kotlin有一个控制器方法,我想返回aResponseEntity<Test>ResponseEntity<Error>

如何在Kotlin进行这项工作?我曾尝试提出ResponseEntitiy<Any>ResponseEntity<*>但Kotlin总是抱怨。

那么如何使返回类型真正成为泛型呢?

@GetMapping
fun test(): Mono<ResponseEntity<?????>>
{
    return Mono.just(1)
        .map { ResponseEntity.ok(Test("OK") }
        .switchIfEmpty(Mono.just(ResponseEntity.badRequest().body(Error("Error"))))
}
阿列克谢·罗曼诺夫(Alexey Romanov)

您还需要更改主体,以便为每个调用提供正确的类型:

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情况,但事实并非如此。

(注意:我目前无法测试,因此可能需要一些修复)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章