【问题标题】:Kotlin and Generic Return Type with Springs ResponseEntityKotlin 和带有 Springs ResponseEntity 的通用返回类型
【发布时间】:2018-04-14 09:10:46
【问题描述】:

假设我在 Spring 中有一个带有 Kotlin 的控制器方法,我想返回 ResponseEntity<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"))))
}

【问题讨论】:

    标签: kotlin spring-webflux


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的快速帮助。奇迹般有效!只有 switchIfEmpty 案例中的第二个as ResponseEntity&lt;*&gt; 不是必需的。
    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 2020-01-06
    • 2020-03-28
    • 1970-01-01
    相关资源
    最近更新 更多