Effective Enums in Kotlin with reverse lookup?

后端 未结 12 1709
野性不改
野性不改 2020-11-30 01:40

I\'m trying to find the best way to do a \'reverse lookup\' on an enum in Kotlin. One of my takeaways from Effective Java was that you introduce a static map inside the enum

12条回答
  •  执念已碎
    2020-11-30 02:00

    Came up with a more generic solution

    inline fun > findEnumConstantFromProperty(predicate: (T) -> Boolean): T? =
    T::class.java.enumConstants?.find(predicate)
    

    Example usage:

    findEnumConstantFromProperty { it.value == 1 } // Equals Type.A
    

提交回复
热议问题