Is this the correct way to turn an enum (in a util...
# android
f
Is this the correct way to turn an enum (in a utility class) to a localized readable string?
Copy code
fun getHumanReadableName(context: Context) =
            context.getString(
                when (this) {
                    POMODORO -> R.string.pomodoro
                    SHORT_BREAK -> R.string.short_break
                    LONG_BREAK -> R.string.long_break
                }
            )
j
Screenshot_20210410-180812.jpg
🤩 1
e
that's one way to do it. another: enum class Time(@StringRes val key) { POMODORO(R.string.pomodoro), fun getHumanReadableName(context: Context) = context.getString(key) }
👍 1
f
@Javier that's actually pretty cool
@Javier Although then I can't pass the context
j
Abstract fun should allow pass the context I think
e
which solution I'd choose depends on the situation. if it's always getString(constant), override fun in each enum is overkill IMO. but if there's more variation, then it may be appropriate
l
Interesting article from Hannes Dorfman on the subject: https://hannesdorfmann.com/abstraction-text-resource/
j
it is not a good idea doing that
f
@Javier What are you referring to? I'm calling this method from the fragment so the locale should be updated properly
j
I was talking about the abstraction text resource post, there is no problem if you are using it on Fragments
f
ah, thank you
🙂 1