```enum class PacketType(val id: Short, vararg ali...
# announcements
d
Copy code
enum class PacketType(val id: Short, vararg aliases: String) {
    CUSTOM_PAYLOAD(0), KEEP_ALIVE(1), LATENCY(2);

    companion object {
        private val PACKETS_BY_ID = mutableMapOf<Short, PacketType>()
        private val PACKETS_BY_ALIAS = mutableMapOf<String, PacketType>()

        fun fromId(id: Short): PacketType? = PACKETS_BY_ID[id]
        fun fromName(id: String): PacketType? {
            return try {
                valueOf(id)
            } catch (e: IllegalArgumentException) {
                PACKETS_BY_ALIAS[id]
            }
        }
    }

    init {
        PacketType.PACKETS_BY_ID[id] = this
        for (alias in aliases) {
            PacketType.PACKETS_BY_ALIAS[alias] = this
        }
    }

    operator fun get(id: Short) = fromId(id)
    operator fun get(id: String) = fromName(id)
}
For some reason, PACKETS_BY_ID and PACKETS_BY_ALIAS don't get initialized
r
They'll be initialized lazily, afaik, but they should be there by the time you use them. What error are you seeing? Can you share code to reproduce it?
d
Exception in thread "main" java.lang.ExceptionInInitializerError
at me.schooltests.sttelnet.client.MainKt.main(Main.kt:22)
at me.schooltests.sttelnet.client.MainKt.main(Main.kt)
Caused by: java.lang.NullPointerException
at me.schooltests.sttelnet.client.packet.PacketType.<init>(PacketType.kt:23)
at me.schooltests.sttelnet.client.packet.PacketType.<clinit>(PacketType.kt:6)
I think that the important part is line 23 (
Copy code
PacketType.PACKETS_BY_ID[id] = this
) It's not really possible to share everything to reproduce, but I found this post https://discuss.kotlinlang.org/t/initialization-order-of-companion-object-and-initializers-in-an-enum/2476