【问题标题】:Filter list of enums by multiple enum constants ("types" of the enum)[Kotlin]通过多个枚举常量过滤枚举列表(枚举的“类型”)[Kotlin]
【发布时间】:2021-11-03 09:37:21
【问题描述】:

我有一个相同枚举对象的枚举常量(类型)列表。如何按多个常量过滤列表?

我试过这个:

val list = dataList.filter {
            when(it.type){
                Type.ACTIVE,
                Type.RENEWED,
                Type.OTHER -> {}
            }
        }

【问题讨论】:

  • 既然要过滤列表,有没有考虑过使用filter?所以你得到:list.filter {it == MyEnumClass.type}。其中it 代表您的列表元素,MyEnumClass.type 代表您的首选类型。
  • 是的,当我需要按多种类型进行过滤时,我该怎么做? (我已经更新了我的问题)
  • 您要么执行list.filter { it == type1 || it == type2 || it == type3 },要么执行Ivo Beckers 建议的when 语句(顺便说一句,when 语句更好)

标签: kotlin enums


【解决方案1】:

这应该可行:

val list = dataList.filter {
    when(it.type){
        Type.ACTIVE,
        Type.RENEWED,
        Type.OTHER -> true
        else -> false
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2012-09-16
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多