Home > OS >  Access Kotlin Interface/Class property by string key?
Access Kotlin Interface/Class property by string key?

Time:07-30

I need to access a class instance property similar to accessing a map in Kotlin.

For a map it goes like this

val myMap: Map<String, String> = mapOf("foo" to "bar")
assertThat(myMap["foo"]).isEqualTo("bar"

Now I want something similar to a class

data class House(
  val street: String
)

// pseudo code wish
fun foo() {
  val valueOfFoo: String = House::class.members["foo"].callGet()
}

I read into reflection but can't find a way to call it. I know the problem somewhat is that there is no class instance passed or specified. However I wonder if there is such thing?

val house = House("Baker Street 5")
val valueOfFoo: String = House::class.members["foo"].callGetWithInstance(house)
   
assertThat(valueOfFoo).isEqualTo("Baker Street 5")

CodePudding user response:

Sure. declaredMemberProperties gives you a collection of KProperty1, which has a get method.

Just write something like

House::class.declaredMemberProperties.find { it.name == "street" }!!.get(house)
  • Related