Kotlin:具有关联值的枚举; “枚举项”内的函数得到“未解决的引用”错误

时间:2018-11-09 21:52:18

标签: android kotlin

我需要创建一个事件列表,并使用字符串作为名称,将事件对列表作为属性,某些事件属性是静态值,某些事件需要动态更改,因此我在enum entry内创建了特定的函数来更新它,但遵循错误unresolved reference

实际上,我要实现的是带有相关值的枚举列表, 像这些文章提到的那样:

由于我有100多个事件,其中95%是静态事件,因此在运行时仅需要更新其中几个,因此密封类可能不适合我的情况:

    enum class Event(val eventName: String, vararg eventProperties: Pair<String, String?>) {
        LOGIN_CLICKED("Login", ("View" to "button clicked")),

        LOGIN_SUCCEED("Login", ("Type" to "succeed")),

        LOGIN_ERROR("Login") {
            fun errorMessage(errorMessage: String) {
                eventProperties = listOf("ErrorType" to errorMessage)
            }
        },

        // ... some other events

        LIST_ITEM_CLICKED("LIST") {
            fun listItemName(itemName: String) {
                eventProperties = listOf("View" to itemName)
            }
        };

        var eventProperties: List<Pair<String, String?>>? = listOf(*eventProperties)


// Although this approach can fix my problem, but I don't prefer it,
// because these functions are only meaningful to specific enum item,
// I don't want them be opened to all enum items.
//
//        fun errorMessage(errorMessage: String) {
//            eventProperties = listOf("ErrorType" to errorMessage)
//        }

//        fun listItemName(itemName: String) {
//            eventProperties = listOf("View" to itemName)
//        }
    }

    fun main(args: Array<String>) {

        // unresolved reference
        println(Event.LOGIN_ERROR.eventProperties)
        Event.LOGIN_ERROR.errorMessage("error password")
        println(Event.LOGIN_ERROR.eventProperties)
    }

1 个答案:

答案 0 :(得分:1)

  

由于我有100多个事件,其中95%是静态的,因此在运行时仅需要更新其中几个,因此密封类可能不适合我的情况

为什么不呢?如果您对声明稍长一些感到困扰:

object LoginClicked : Event("Login", mapOf("View" to "button clicked")) 
\\ vs
LOGIN_CLICKED("Login", mapOf("View" to "button clicked"))

您可以为他们创建一个助手enum class

sealed class Event(val eventName: String, val eventProperties: Map<String, String?>) {
   enum class Basic(val eventName: String, val eventProperties: Map<String, String?>) {
        LOGIN_CLICKED("Login", mapOf("View" to "button clicked")),
        LOGIN_SUCCEED("Login", mapOf("Type" to "succeed")),       
        ...
   }

   class BasicEvent(b: Basic) : Event(b.eventName, b.eventProperties)

   class LoginError(errorMessage: String) : Event("Login", mapOf("ErrorType" to errorMessage))
   ...
}