繁体   English   中英

Kotlin处理变量返回函数的类型

[英]kotlin handling variable return type of function

假设我有多个DTO,例如:

data class ActionDetailDTO(
    @JsonProperty("priority")
    val priority: String,
    @JsonProperty("reason")
    val reason: String
)

data class IntroDTO(
    @JsonProperty("name")
    val name: String,
    @JsonProperty("number")
    val number: String
)

当我解析它们时,我将这些dto的json存储为字符串:

    fun parseStringBasedOnType(action: SomeDTOType) :Any{
    val obj = when (action.actionType){
            "CREATED" -> objectMapper.readValue(action.actionDetails, ActionDetailDTO::class.java)
            "INTRO" -> objectMapper.readValue(action.actionDetails, IntroDTO::class.java)

            else -> "hh"
        }
        return obj
     }

所以:

val nn = parseStringBasedOnType(SomeActionObject) //type: CREATED
if(nn.actionType == "CREATED"){
    println(nn.reason)
}

这显然行不通,如何处理?

您可以使用actionType方法定义公共接口,也可以actionType值:

if(nn is ActionDetailDTO) {
    println(nn.reason)
}

或者使用when ,如果你打算做一些对其他类型来说:

when(nn) {
  is ActionDetailDTO -> println(nn.reason)
  is IntroDTO -> println(nn.number)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM