简体   繁体   中英

kotlin handling variable return type of function

Suppose I've multiple DTOs, like:

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
)

and I've a json of these dtos stored as strings, when I parse them doing something like this:

    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
     }

so:

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

This obviously does not work, how can this be handled?

You could either define a common interface with an actionType method or cast the values:

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

Or use when if you plan to do something for the other type too:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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