0

ELevel is enum class in a top function of Koltin, but the Code A is hard code.

So I try to use Code B, but it's wrong, how can I fix it?

Code A

enum class ELevel(val label:String){
   Whisper("Whisper"),
   Quiet("Quiet Library") 
}

Code B

enum class ELevel(val label:String){
  Whisper(getApplicationContext().getString(R.String.Whisper)),
   Quiet(getApplicationContext().getString(R.String.Quiet)) 
}
    
<resources>
    <string name="Whisper">Whisper</string>
    <string name="Quiet">Quiet Library</string>    
</resources>
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

4

I would do it like this:

enum class ELevel(private val labelId: Int){
    Whisper(R.string.whisper),
    Quiet(R.string.quiet);

    fun getLabel(context: Context) =
        context.getString(labelId)
}

The downside is you have to pass a Context instance each time, but it's the safer way to do it.

An alternate way to do it is like this:

enum class ELevel(private val labelId: Int){
    Whisper(R.string.whisper),
    Quiet(R.string.quiet);

    lateinit var label: String
        private set

    companion object {
        fun initialize(context: Context) {
            for (value in EValue.values()) value.label = context.getString(value.labelId)
        }
    }
}

And then in your MainActivity.onCreate(), call ELevel.initialize(applicationContext). But you have to be careful not to use the label property in any code that is run before onCreate(), like in a property initializer. If you use the enum in any Services, then you need to call initialize() in your Application subclass's onCreate() instead, but then you need to watch out for this issue.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154