[英]kotlin handling variable return type of function
Suppose I've multiple DTOs, like: 假设我有多个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
)
and I've a json of these dtos stored as strings, when I parse them doing something like this: 当我解析它们时,我将这些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
}
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: 您可以使用actionType
方法定义公共接口,也可以actionType
值:
if(nn is ActionDetailDTO) {
println(nn.reason)
}
Or use when
if you plan to do something for the other type too: 或者使用when
,如果你打算做一些对其他类型来说:
when(nn) {
is ActionDetailDTO -> println(nn.reason)
is IntroDTO -> println(nn.number)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.