Android Kotlin中如何匹配字符串与枚举属性获取对应code值
Kotlin 枚举匹配功能实现
实现思路
遍历Data枚举的所有实例,匹配nameOfCode属性与目标字符串相等的枚举项,返回该项的code属性即可。
代码实现
单次调用场景
如果匹配逻辑使用频率低,直接遍历枚举即可:
var stringValue: String = "ort" // 匹配nameOfCode,返回对应code,匹配不到返回null val targetCode = Data.values().find { it.nameOfCode == stringValue }?.code // 如果需要匹配不到时返回默认值,写法如下 val targetCodeWithDefault = Data.values().find { it.nameOfCode == stringValue }?.code ?: "" // 示例中stringValue为"ort"时,targetCode取值为"70"
高频调用优化
如果匹配逻辑需要频繁调用,提前构建映射缓存提升性能:
// 全局缓存,启动时仅初始化一次 val nameToCodeMap = Data.values().associate { it.nameOfCode to it.code } // 调用时直接读取缓存,时间复杂度O(1) val targetCode = nameToCodeMap[stringValue] ?: ""
可选:忽略大小写匹配
如果需要支持大小写不敏感的匹配,修改匹配条件即可:
// 匹配时忽略大小写,比如"Ort"也能匹配到ORT枚举项 val targetCode = Data.values().find { it.nameOfCode.equals(stringValue, ignoreCase = true) }?.code
内容的提问来源于stack exchange,提问作者sri
相关产品推荐
相关产品推荐

