You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:36:06