Miller Dong
Miller Dong

Reputation: 99

In Kotlin, is there a way to add one more value into enum by a function call?

I have an enum, for example

enum class User(val userInfo: UserInfo){
    USER_A( NewUser(A) ),
    USER_B( NewUser(B) ),
    USER_C( NewUser(C) ),
}

Now I want to add one user to the User enum, can I do something like this?

User.add( "USER_D", NewUser(D) )

From my point of view, since enum is constant and created at compile time, I think it's impossible. But dose anyone know a workaround that can realize something similar?

Thanks in advance!

Upvotes: 1

Views: 1329

Answers (2)

Pawan Soni
Pawan Soni

Reputation: 936

No, you cannot modify types at runtime. You could emit new types, but modifying existing ones is not possible. Having an enum value is, in my opinion, preferable over dictionaries or list based solution as one uses less memory and no thread side effects.

Upvotes: 1

Iaroslav Postovalov
Iaroslav Postovalov

Reputation: 2453

Enum properties are converted to plain static final instances. I think the closest thing is to use a simple map:

class User(val info: UserInfo)
val users = mutableMapOf("USER_A" to User(A))

Unfortunately, there are no accessors checked in compiletime like users.USER_A, but it is not completely possible since the map is mutated in runtime.

Upvotes: 1

Related Questions