用于在枚举中按键返回 Map 值的函数

Function to return the value of a Map by key in an enum

提问人:Fares Mahmoud 提问时间:2/7/2023 最后编辑:Z-100Fares Mahmoud 更新时间:2/7/2023 访问量:50

问:

我有一个枚举类,它将语言区域设置映射到列表。

如何修复伴随对象中的函数getReservationFrequencies 要根据区域设置(键)返回映射的值?

enum class ReservationFrequencies(val frequencies: Map<Language, List<ReservationFrequency>>)  {
    APPLICATION(mapOf(
            Language.en to listOf(
                    ReservationFrequency(0,"once",0),
                    ReservationFrequency(1,"Monthly",2),
                    ReservationFrequency(2,"Quarterly",5),
                    ReservationFrequency(3,"Semi-annually",5),
                    ReservationFrequency(4,"Annually",5)
            ),
            Language.ar to listOf(
                    ReservationFrequency(0,"مرة واحده",0),
                    ReservationFrequency(1,"شهرياً",2),
                    ReservationFrequency(2,"ربع سنوياً",5),
                    ReservationFrequency(3,"نصف سنوياً",5),
                    ReservationFrequency(4," سنوياً",5)
            )
    ));
}

我尝试创建一个伴随对象,其中包含一个返回列表的函数

companion object {
    fun getReservationFrequencies(locale: String?) : List<ReservationFrequency> {
        val reservationFrequencyDtos = mutableListOf<ReservationFrequency>()
        reservationFrequencies.values()
            .filter { locale!!.contains(it.name)}
            .forEach() {
                ReservationFrequency.add(ReservationFrequency(code = it.frequencies))
            }
    }
}

我期待一个基于语言环境的List<ReservationFrequency>

Kotlin 枚举类

评论

0赞 Z-100 2/7/2023
您能否向我们提供有关语言和预订频率的更多详细信息,以实现可创建性?

答:

0赞 AndrewL 2/7/2023 #1

可能就是这个

fun getReservationFrequencies(locale: String?) : List<ReservationFrequency> =
    ReservationFrequencies.APPLICATION.frequencies.filter { 
        it.key.name == locale // I don't know the specifics of how to match the String locale arg against Language
    }.map {
        it.value
    }.first()