I'm trying to associate an enum class with a name/...
# getting-started
b
I'm trying to associate an enum class with a name/translation; I can do that for each instance so I can fill an HTML select drop down with translated values, but I need a label for the select as well; now the issue is that I basically need either an annotation which is not available on non JVM platforms or a static member but I can't really put an interface on a class that says that the Companion object of this class has a i18nKey member. Is there a good way to solve that?
1
l
There is some missing information here. There is no single way to do localisation in Kotlin. The way you phrase your question leads me to believe that you are using some specific localisation framework that requires you to specify translatable information in a specific way. You're also not even mentioning what platform you're using, nor what kind of UI system you're working with. If provide some context it will probably be possible to answer your question.
b
I'm currently implementing the JS parts using i18next but Java & others work in a similar way
basically I'm passing "something.something.x" as the key to the framework and I want to persist that key on the enum itself
I know that there other frameworks that might do translation differently, but I'm fine with the coupling it introduces since it significantly simplifies translation
back to the original question: I simply created a Translatable interface
Copy code
interface Translatable {
    val i18nKey: String
}
and implement that in the relevant enum classes for each value; however I'm lacking a way to retrieve a key for the class itself
l
Why not just add a
name
field to the enum?
Something like
enum class Foo(val name: String) { FOO("xyz"), BAR("qwert") }
Or you can build the key from the class name, using
Foo.FOO::class.name
b
because the name field would be tied to the instance, not the class
as for class name: I'm not sure if that is retained or minified away
plus there might be similar class names in different packages
l
Instead of using enums, you can use objects:
Copy code
sealed class Parent {
  object Foo : Parent
  object Bar : Parent
}
And then use the class name. But now you say you want named classes.
In those cases, ::class.name is the right way to go, and it won't be minified.
Sorry,
Foo::class.simpleName
.
It's
.qualifiedName
that may not be available.
As per the documentation: "The simple name of the class as it was declared in the source code, or
null
if the class has no name (if, for example, it is a class of an anonymous object)"
b
thank you