我们有一些返回第三方SDK的代码,该代码返回“是否?”。而且我们必须强制转换(如果它强制转换并解析)。由于我们的类型转换是通用的,因此如果不编写5个类型转换,我将无法弄清楚如何简化此转换。在Swift中,这似乎容易得多。有没有更好的方法来进行这些投射?
private fun parseOrganizations(payload: Any?): List<UserOrganization> {
val organizations = mutableListOf<UserOrganization>()
payload?.let { userData ->
if (userData is Map<*, *>) {
val orgJsonList = userData["organizations"]
if (orgJsonList is List<*>) {
for (jsonMap in orgJsonList) {
if (jsonMap is Map<*, *>) {
val id = jsonMap["id"] as? String
val name = jsonMap["name"] as? String
val role = jsonMap["role"] as? String
val isActive = jsonMap["isActive"] as? Boolean
val isVerified = jsonMap["isVerified"] as? Boolean
if (id != null && name != null && role != null && isActive != null && isVerified != null) {
val org = UserOrganization(id, name, role, isActive, isVerified)
organizations.add(org)
}
}
}
}
}
}
return organizations
}
谢谢大家。
答案 0 :(得分:2)
您可以避免很多嵌套的if
,只需将其更改为?.let
并将for
更改为map
即可。在这种情况下,代码将是平坦且可读的
fun parseOrganizations(payload: Any?) {
payload
?.let { it as? Map<*, *> }
?.let { it["organizations"] as? List<*> }
?.mapNotNull { if (it is Map<*, *>) UserOrganization.fromMap(it) else null }
?.map { organizations.add(it) }
}
但是我们应该处理从UserOrganization
开始创建包含组织详细信息的Map
。老实说,我想不出一个真正优雅的方法。但是最好创建外部函数或类似的东西来封装回退逻辑:
class UserOrganization(
val id: String,
val name: String,
val role: String,
val isActive: Boolean,
val isVerified: Boolean
){
companion object {
fun fromMap(org: Map<*,*>): UserOrganization? =
if (org.keys.containsAll(listOf("id", "name", "role", "isActive", "isVerified"))) {
UserOrganization(
id = org["id"] as? String ?: "Unknown Id",
name = org["name"] as? String ?: "Unknown name",
role = org["role"] as? String ?: "Unknown role",
isActive = org["isActive"] as? Boolean ?: false,
isVerified = org["isVerified"] as? Boolean ?: false
)
} else null
}
}
我不能打赌它可以100%正确地工作,但是我想我可以证明这个想法。