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

Kotlin中如何根据数据库存储的Int值解析Flag枚举的多个匹配项

Kotlin 位掩码枚举多匹配实现方案

你当前的枚举定义属于典型的位掩码使用场景,每个枚举值都是2的幂次,天然适配按位运算的多匹配逻辑,具体实现如下:

1. 基础多匹配实现

遍历全部枚举值,通过按位与运算判断当前枚举是否被包含在传入的Int值中:

// 工具方法实现
fun getMatchedProfileFlags(value: Int): List<ProfileDisplayFlags> {
    return ProfileDisplayFlags.values().filter { flag ->
        (flag.number and value) != 0
    }
}

// 调用示例
val configValue = 3
val matchedFlags = getMatchedProfileFlags(configValue) 
// 输出结果:[Address, PhoneNumber]

2. 便捷扩展函数封装

可以给Int类型扩展对应方法,减少业务代码的冗余:

// 扩展方法:将Int转换为匹配的枚举列表
fun Int.toProfileDisplayFlags(): List<ProfileDisplayFlags> {
    return ProfileDisplayFlags.values().filter { 
        (it.number and this) != 0 
    }
}

// 扩展方法:判断当前Int是否包含指定枚举项
fun Int.hasProfileFlag(flag: ProfileDisplayFlags): Boolean {
    return (this and flag.number) != 0
}

// 调用示例
val config = 3
val showList = config.toProfileDisplayFlags()
val needShowPhone = config.hasProfileFlag(ProfileDisplayFlags.PhoneNumber) // 返回true

3. 多枚举合并为Int(可选)

如果需要把选中的多个枚举项回写为Int存入数据库,可以用按位或实现:

fun combineProfileFlags(vararg flags: ProfileDisplayFlags): Int {
    return flags.fold(0) { acc, flag -> acc or flag.number }
}

// 调用示例
val saveValue = combineProfileFlags(ProfileDisplayFlags.Address, ProfileDisplayFlags.PhoneNumber)
// 输出结果:3

内容的提问来源于stack exchange,提问作者Eman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:24:03