jeudi 23 avril 2020

Getting the name of a static member property in Kotlin

I have a javaclass like this, inside of a Kotlin project:

public final class BuildConfig {
  public static final String FOO = "HelloWorld";
  public static final String ALT_FOO = "HelloWorldAlt";
}

How can I get a String with the value FOO? (not the value of the field, the name of the field)

i.e. val theName = "FOO"

For example later on I will have a map.

val map = mapOf("FOO" to "HelloWorldAlt", "BAR" to "CoronaGotMeInside")

and I want to do the below:

val result = map[theName]
println(result)
// HelloWorldAlt

I know I can get all the field values like the below, but I can't figure how to get the static member variable name off of a single static var. I don't want to iterate all staticProperties. I want to explicitly look one up.

val notResult = BuildConfig::class.staticProperties.filter { it.name == "FOO" }[0].getter.call()
println(notResult)
// HelloWorld

As an example of a not iterative solution, I want something like this:

val theName = BuildConfig.FOO::variableName() // Totally made up, but I want to act on the singular constant, not on a collection 

This would allow me to have some compile time confidence when using the variables name a map key. Crazy I know.





Aucun commentaire:

Enregistrer un commentaire