7

I am new to Kotlin and I have an enum containing many values, those values refer to different states my application has.

Now I need to log something whenever the app enters a state but some state in the enum can log more than one thing (based on other parameters coming from outside the app) and some state does not need to log something.

Here is my enum:

enum class StateName(vararg log: String) {
    FIRST_CONNECTION(), // no parameter here
    AUTHORIZATION_CHECK("message 1", "message 2"),
    HANDSHAKE_SUCCESS("message")
    //...
}

If had declared the enum with a single obligatory parameter StateName(var log: String) I could have used HANDSHAKE_SUCCESS.log to retrieve its value but with vararg the IDE (android studio) does not find log at all.

So how can I retrieve my string with something like log[0]?

Note:

  • My enum is already defined (without parameters) and in use in my application and I can't use a different method of changing the actual state/adding a logging functionality
  • I need to use Kotlin even if I just started learning as the project was written with this language so I just want to know if (and how) I can do that.

2 Answers 2

16

You need to change it to:

enum class StateName(vararg val log: String)

This way you can access the log

1
  • 2
    Wow, was that simple? I feel dumb. Thank you May 30, 2019 at 14:33
-1

You need to create a variable inside enum which will hold all the arguments like below:

  enum class StateName( vararg log: String) {
        FIRST_CONNECTION(), // no parameter here
        AUTHORIZATION_CHECK("message 1", "message 2"),
        HANDSHAKE_SUCCESS("message");

        public var logParams:Array<out String>

        init{
             logParams=log
        }

    }

And to print the param corresponding to particular enum, you can iterate like below:

 for (item in StateName.AUTHORIZATION_CHECK.logParams) {
           println("item = "+item)
 }
1
  • Doing simply vararg val log: String works
    – milosmns
    Aug 1, 2021 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.