【问题标题】:kotlin handling variable return type of functionkotlin 处理函数的变量返回类型
【发布时间】:2018-08-12 04:53:21
【问题描述】:

假设我有多个 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)
}

这明明不行,怎么处理?

【问题讨论】:

    标签: function types kotlin


    【解决方案1】:

    您可以使用actionType 方法定义一个通用接口,也可以转换值:

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

    如果您也打算为其他类型做某事,请使用when

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 2013-10-14
      • 2023-03-07
      相关资源
      最近更新 更多